如何使用AFNetwork的AFHTTPRequestOperationManager设置HTTP请求正文?

我正在使用AFHTTPRequestOperationManager(2.0 AFNetworking库)REST POST请求。 但是pipe理者只需要调用参数。

-((AFHTTPRequestOperation *)POST:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; 

我需要设置一个string的HTTP请求正文。 我怎样才能使用AFHTTPRequestOperationManager? 谢谢。

我有同样的问题,并通过添加代码来解决它,如下所示:

 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10]; [request setHTTPMethod:@"POST"]; [request setValue:@"Basic: someValue" forHTTPHeaderField:@"Authorization"]; [request setValue: @"application/json" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody: [body dataUsingEncoding:NSUTF8StringEncoding]]; AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request]; op.responseSerializer = [AFJSONResponseSerializer serializer]; [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"JSON responseObject: %@ ",responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Error: %@", [error localizedDescription]); }]; [op start]; 

为AFHTTPRequestOperationManager

 [requestOperationManager.requestSerializer setValue:@"your Content Type" forHTTPHeaderField:@"Content-Type"]; [requestOperationManager.requestSerializer setValue:@"no-cache" forHTTPHeaderField:@"Cache-Control"]; // Fill parameters NSDictionary *parameters = @{@"name" : @"John", @"lastName" : @"McClane"}; // Customizing serialization. Be careful, not work without parametersDictionary [requestOperationManager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, NSDictionary *parameters, NSError *__autoreleasing *error) { NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:nil]; NSString *argString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; return argString; }]; [requestOperationManager POST:urlString parameters:parameters timeoutInterval:kRequestTimeoutInterval success:^(AFHTTPRequestOperation *operation, id responseObject) { if (success) success(responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { if (failure) failure(error); }]; 

检查一下这个方便的方法(POST:parameters:success:failure)在底层做什么,并自己去实际访问实际的NSMutableRequest对象。

我正在使用AFHTTPSessionManager而不是AFHTTPRequestOperation,但我想象的机制是类似的。

这是我的解决scheme:

  1. 安装会话pipe理器(头文件等)

  2. 手动创buildNSMutable请求,并添加我的HTTPBody,基本上复制粘贴在该便利方法的代码。 看起来像这样:

     NSMutableURLRequest *request = [manager.requestSerializer requestWithMethod:@"POST" URLString:[[NSURL URLWithString:<url string>] absoluteString] parameters:parameters]; [request setHTTPBody:[self.POSTHttpBody dataUsingEncoding:NSUTF8StringEncoding]]; __block NSURLSessionDataTask *task = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) { if (error) { // error handling } else { // success } }]; [task resume]; 

如果你在AFNetworking的源头上挖掘一点,你会发现在POST方法的情况下,参数被设置成你的HTTP请求的主体。

每个键值字典对以表格key1=value1&key2=value2forms添加到主体中。 对由“&”分隔。

AFURLRequestSerialization.m中searchapplication/x-www-form-urlencoded

如果string只是一个string,而不是键值对,那么你可以尝试使用AFQueryStringSerializationBlock http://cocoadocs.org/docsets/AFNetworking/2.0.3/Classes/AFHTTPRequestSerializer.html#//api/name/ setQueryStringSerializationWithBlock :但这只是我的猜测。

您可以创build您自己的AFHTTPRequestSerializer的自定义子类,并将其设置为您的AFHTTPRequestOperationManager的requestSerializer。

在这个自定义requestSerializer中,你可以覆盖

 - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request withParameters:(id)parameters error:(NSError *__autoreleasing *)error; 

在你实现这个方法的过程中,你可以访问NSURLRequest ,所以你可以这样做

 - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request withParameters:(id)parameters error:(NSError *__autoreleasing *)error { NSURLRequest *serializedRequest = [super requestBySerializingRequest:request withParameters:parameters error:error]; NSMutableURLRequest *mutableRequest = [serializedRequest mutableCopy]; // Set the appropriate content type [mutableRequest setValue:@"text/xml" forHTTPHeaderField:@"Content-Type"]; // 'someString' could eg be passed through and parsed out of the 'parameters' value NSData *httpBodyData = [someString dataUsingEncoding:NSUTF8StringEncoding]; [mutableRequest setHTTPBody:httpBodyData]; return mutableRequest; } 

你可以看一下AFJSONRequestSerializer的实现, AFJSONRequestSerializer一个设置自定义HTTP正文内容的例子。

 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; manager.requestSerializer = [AFJSONRequestSerializer serializer]; [manager POST:url parameters:jsonObject success:^(AFHTTPRequestOperation *operation, id responseObject) { //success } failure:^(AFHTTPRequestOperation *operation, NSError *error) { //fail }]; 

这是我find的最好,最简洁的方式。

可能是我们可以使用NSMutableURLRequest,这里是代码:

 NSURL *url = [NSURL URLWithString:yourURLString]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; [request setHTTPMethod:@"POST"]; NSData *JSONData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:nil]; NSString *contentJSONString = [[NSString alloc] initWithData:JSONData encoding:NSUTF8StringEncoding]; [request setHTTPBody:[contentJSONString dataUsingEncoding:NSUTF8StringEncoding]]; NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; [connection start];