简体   繁体   中英

iOS AFNetworking GET/POST Parameters

I want to do a POST request with AFNetworking which contains GET and POST parameters.

I am using this code:

NSString *urlString = [NSString stringWithFormat:@"upload_stuff.php?userGUID=%@&clientGUID=%@",
                           @"1234",
                           [[UIDevice currentDevice] identifierForVendor].UUIDString];

    NSString *newUrl = @"https://sub.domain.com";

    NSURL *baseURL = [NSURL URLWithString:newUrl];

    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
    [httpClient defaultValueForHeader:@"Accept"];

    NSDictionary *getParams = [NSDictionary dictionaryWithObjectsAndKeys:
                            @"1234", @"userGUID",
                            [[UIDevice currentDevice] identifierForVendor].UUIDString, @"clientGUID",
                            nil];
    NSDictionary *postParams = [NSDictionary dictionaryWithObjectsAndKeys:
                                [@"xyz" dataUsingEncoding:NSUTF8StringEncoding], @"FILE",
                                nil];

    [httpClient postPath:urlString parameters:postParams success:^(AFHTTPRequestOperation *operation, id responseObject) {


    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error retrieving data: %@", error);
    }];

Now I have two questions:

  • How can I use BOTH GET and POST dictionaries in the same request? For the time, I am integrating the GET dictionary into the URL and using only the POST dictionary ( [httpClient postPath:...] )

  • I am getting an error from the server stating that the parameter "FILE" is missing. Unfortunately I can't examine any server logs (not my server). But using a standard NSURLConnection I was able to send requests with the FILE parameter to this server. So what is going wrong here?

Stackoverflow for you:

NSData* sendData = [self.fileName.text dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *sendDictionary = [NSDictionary dictionaryWithObject:sendData forKey:@"name"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:remoteUrl];
NSMutableURLRequest *afRequest = [httpClient multipartFormRequestWithMethod:@"POST" 
                                                                       path:@"/photos" 
                                                                 parameters:sendDictionary 
                                                  constructingBodyWithBlock:^(id <AFMultipartFormData>formData) 
                                  {                                     
                                      [formData appendPartWithFileData:photoImageData 
                                                                  name:self.fileName.text 
                                                              fileName:filePath 
                                                              mimeType:@"image/jpeg"]; 
                                  }
                                  ];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:afRequest];
[operation setUploadProgressBlock:^(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) {

    NSLog(@"Sent %d of %d bytes", totalBytesWritten, totalBytesExpectedToWrite);

}];

[operation setCompletionBlock:^{
    NSLog(@"%@", operation.responseString); //Gives a very scary warning
}];

[operation start]; 

By @Igor Fedorchuk from POST jpeg upload with AFNetworking

AFNetworking has no method to setup both GET and POST params. You have to setup GET params to your url, and use [AFHTTPClient requestWithMethod:path:parameters:] setup POST params.

- (NSURLRequest *)requestForPath:(NSString *)path method:(NSString *)method
{
    NSMutableString *pathWithGetParams = [NSMutableString stringWithString:path];
    BOOL hasPathContainsQueryChar = [path rangeOfString:@"?"].location != NSNotFound;
    [pathWithGetParams appendString:hasPathContainsQueryChar ? @"&" : @"?"];
    for (id key in self.getArguments.allKeys)
    {
        if ([key isKindOfClass:[NSString class]])
        {
            NSString *value = self.getArguments[key];
            if ([value isKindOfClass:[NSString class]])
            {
                [pathWithGetParams appendString:[[self class] urlEncode:key]];
                [pathWithGetParams appendString:@"="];
                [pathWithGetParams appendString:[[self class] urlEncode:value]];
                [pathWithGetParams appendString:@"&"];
            }
        }
    }

    NSString *upperCaseMethod = [method uppercaseString];
    BOOL isMethodInGet = [upperCaseMethod isEqualToString:@"GET"];
    NSURLRequest *request = [[self shareAFClient] requestWithMethod:method
                                                               path:pathWithGetParams
                                                         parameters:isMethodInGet ? nil : self.postArguments];
    return request;
}

+ (NSString *)urlEncode:(NSString *)stringToEncode
{
    return [self urlEncode:stringToEncode usingEncoding:NSUTF8StringEncoding];
}

+ (NSString *)urlEncode:(NSString *)stringToEncode usingEncoding:(NSStringEncoding)encoding
{
    return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
                                                                                 (__bridge CFStringRef)stringToEncode,
                                                                                 NULL,
                                                                                 (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
                                                                                 CFStringConvertNSStringEncodingToEncoding(encoding));
}

+ (NSString*)urlDecode:(NSString *)stringToDecode
{
    return [self urlDecode:stringToDecode usingEncoding:NSUTF8StringEncoding];
}

+ (NSString*)urlDecode:(NSString *)stringToDecode usingEncoding:(NSStringEncoding)encoding
{
    return (__bridge_transfer NSString *) CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
                                                                                                  (__bridge CFStringRef)stringToDecode,
                                                                                                  (CFStringRef)@"",
                                                                                                  CFStringConvertNSStringEncodingToEncoding(encoding));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM