19

I am using AFHTTPRequestOperationManager (2.0 AFNetworking library) for a REST POST request. But the manager only have the call to set the parameters.

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

I need to set HTTP request body with a string as well. How can I do it using the AFHTTPRequestOperationManager? Thanks.

4

7 回答 7

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];
于 2013-12-28T07:06:50.453 回答
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);
}];
于 2016-01-05T16:11:11.787 回答
6

检查该便捷方法(POST:parameters:success:failure)在后台做了什么,并自己动手以访问实际的 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];
    
于 2013-11-08T08:59:50.110 回答
4

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

在这个自定义 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 正文内容的示例。

于 2015-02-25T14:17:53.910 回答
4

如果您深入研究 AFNetworking 的来源,您会发现POST方法参数被设置到 HTTP 请求的正文中。

每个键值字典对都以 form 的形式添加到正文中key1=value1&key2=value2。对由 & 符号分隔。

application/x-www-form-urlencodedAFURLRequestSerialization.m中搜索。

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

于 2013-12-23T00:46:19.630 回答
4
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
}];

这是我发现的最好和最简洁的方法。

于 2015-05-05T06:10:24.073 回答
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];
于 2014-10-22T10:41:19.357 回答