iOS AFNetworking GET / POST参数

时间:2013-03-24 22:48:07

标签: ios nsurlconnection afnetworking

我想用AFNetworking做一个包含GET和POST参数的POST请求。

我正在使用此代码:

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);
    }];

现在我有两个问题:

  • 如何在同一个请求中使用BOTH GET和POST词典?当时,我正在将GET字典集成到URL中,并仅使用POST字典([httpClient postPath:...]

  • 我从服务器收到一条错误,指出缺少参数“FILE”。不幸的是我无法检查任何服务器日志(不是我的服务器)。但是使用标准NSURLConnection我能够将带有FILE参数的请求发送到此服务器。那么这里出了什么问题?

2 个答案:

答案 0 :(得分:0)

Stackoverflow:

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]; 

来自POST jpeg upload with AFNetworking的@Igor Fedorchuk

答案 1 :(得分:0)

AFNetworking无法同时设置GET和POST参数。 您必须将GET参数设置为您的网址,并使用[AFHTTPClient requestWithMethod:path:parameters:]设置POST参数。

- (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));
}