如何使用AFNetwork的AFHTTPRequestOperationManager设置HTTP请求主体?

时间:2013-10-31 17:05:07

标签: ios iphone objective-c ipad afnetworking

我正在使用AFHTTPRequestOperationManager(2.0 AFNetworking库)来发送REST POST请求。但是经理只有调用来设置参数。

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

我还需要使用字符串设置HTTP请求正文。我怎么能用AFHTTPRequestOperationManager来做呢?感谢。

7 个答案:

答案 0 :(得分:31)

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

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

答案 1 :(得分:7)

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

答案 2 :(得分:6)

检查那个方便方法(POST:参数:成功:失败)是做什么的,并亲自动手以获取对实际NSMutableRequest对象的访问权。

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

这是我的解决方案:

  1. 设置会话管理器(标题等)

  2. 手动创建NSMutable请求并添加我的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];
    

答案 3 :(得分:4)

如果您在AFNetworking的源代码中稍微挖掘一下,您会发现在POST方法参数被设置到HTTP请求的正文中时。

每个键值字典对都以key1=value1&key2=value2格式添加到正文中。对由&amp;分隔。登录。

AFURLRequestSerialization.m 中搜索application/x-www-form-urlencoded

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

答案 4 :(得分:4)

您可以创建自己的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的实现内容,了解设置自定义HTTP正文内容的示例。

答案 5 :(得分:3)

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

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

答案 6 :(得分:0)

可能我们可以使用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];