使用JSON body AFNetworking 2.0的POST请求

时间:2015-02-07 00:17:32

标签: ios objective-c afnetworking afnetworking-2

无论如何使用AFNetworking发送带有JSON主体的POST请求〜> 2.0

我尝试过使用:
manager.requestSerializer = [AFJSONRequestSerializer serializer]; manager POST:<url> parameters: @{@"data":@"value"} success: <block> failure: <block>'

但它不起作用。任何帮助是极大的赞赏。 感谢

2 个答案:

答案 0 :(得分:6)

您可以在NSMutableURLRequest中添加您的JSON正文,而不是直接parameters:。请参阅我的示例代码:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// Set post method
[request setHTTPMethod:@"POST"];
// Set header to accept JSON request
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
// Your params
NSDictionary *params = @{@"data":@"value"};
// Change your 'params' dictionary to JSON string to set it into HTTP
// body. Dictionary type will be not understanding by request.
NSString *jsonString = [self getJSONStringWithDictionary:params];

// And finally, add it to HTTP body and job done.
[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:<block> failure:<block>];

希望这会对你有所帮助。快乐的编码! :)

答案 1 :(得分:2)

如果有人在寻找AFNetworking 3.0,这里是代码

NSError *writeError = nil;

NSData* jsonData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:&writeError];
NSString* jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData  timeoutInterval:120];

[request setHTTPMethod:@"POST"];
[request setValue: @"application/json; encoding=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setValue: @"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPBody: [jsonString dataUsingEncoding:NSUTF8StringEncoding]];

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

[[manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {

    if (!error) {
        NSLog(@"Reply JSON: %@", responseObject);

        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            //blah blah
        }
    } else {

        NSLog(@"Error: %@", error);
        NSLog(@"Response: %@",response);
        NSLog(@"Response Object: %@",responseObject);

    }
}] resume];