AFHTTPRequestOperation

AFHTTPRequestOperation

我将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进行操作?谢谢。

最佳答案

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

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

10-06 13:24