最近在做IOS项目的时候, 使用AFNetworking第三方库的时候,提交post请求一直出问题。网上的解决方法都比较杂乱,这里mark一下我最终的解决方法。
post代码块:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"name" : @"1111", @"password" : password};
NSLog(@"%@", parameters);
[manager POST:LoginURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"%@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"========>%@", error.debugDescription);
}];
出现的错误:
Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x7fe238dc6ab0 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.
大概意思也就是返回json数据格式不对。
解决方法:
指定其response的content-type,Json格式为application/json。
方法1.
manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
让其接收json格式数据, 并设置readingAllowFragments。
方法2.
AFHTTPResponseSerializer *s = [[AFHTTPResponseSerializer alloc] init];
s.acceptableContentTypes = [NSSetsetWithObject:@"application/json"];
manager.responseSerializer = s;
这里采用manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];的时候也是不行,虽然manager.responseSerializer也是一个AFHTTPResponseSerializer对象。
扩展:
如果你的服务器指定了content-type,解决方法如下:
AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
[requestSerializer setValue:@"html/text"forHTTPHeaderField:@"Content-Type"];
[requestSerializer setValue:@"html/text"forHTTPHeaderField:@"Accept"];
manager.requestSerializer = requestSerializer;