简体   繁体   English

iOS AFNetworking GET / POST参数

[英]iOS AFNetworking GET/POST Parameters

I want to do a POST request with AFNetworking which contains GET and POST parameters. 我想用AFNetworking做一个包含GET和POST参数的POST请求。

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? 如何在同一请求中使用BOTH GET和POST词典? For the time, I am integrating the GET dictionary into the URL and using only the POST dictionary ( [httpClient postPath:...] ) 当时,我正在将GET字典集成到URL中并仅使用POST字典( [httpClient postPath:...]

  • I am getting an error from the server stating that the parameter "FILE" is missing. 我从服务器收到错误,指出缺少参数“FILE”。 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. 但是使用标准的NSURLConnection我能够将带有FILE参数的请求发送到此服务器。 So what is going wrong here? 那么这里出了什么问题?

Stackoverflow for you: 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]; 

By @Igor Fedorchuk from POST jpeg upload with AFNetworking 来自@ jgor Fedorchuk的POST jpeg上传与AFNetworking

AFNetworking has no method to setup both GET and POST params. AFNetworking无法设置GET和POST参数。 You have to setup GET params to your url, and use [AFHTTPClient requestWithMethod:path:parameters:] setup POST params. 您必须将GET参数设置为您的URL,并使用[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));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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