使用AFNetworking3.0后网络请求由原来的AFHTTPRequestOperationManager变为AFHTTPSessionManager。一般的Post请求变成了这样:
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params[@"phoneNumber"] = @"18000000000";
params[@"password"] = @"123";
AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
[session POST:@"" parameters:@"" progress:params success:nil failure:nil];
最近后台要求我们提交post请求使用JSON格式,如{"password":"123","phoneNumber":"18000000001"};
使用原有请求方式请求报错error:Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: service unavailable (503)"。如图:
无意间发现MJExtension中有将字典转为JSON字符串的方法[params mj_JSONString],然后心里默默称赞了杰哥的强大,看了下转JSON的源码,以为如此简单就可以解决问题。事实证明我还是too young too simple,控制台依旧输出错误error:Error Domain=NSCocoaErrorDomain Code=3840 "No value for key in object around character 7998."。
无奈之下赶紧到github上翻看AFNetworking的文档,发现有这样一句话:
JSON Parameter Encoding
[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
POST http://example.com/
Content-Type: application/json
{"foo": "bar", "baz": [1,2,3]}
立马将这句话加入到网络请求当中:(方法一)
// 获得请求管理者
AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
// 设置请求格式
session.requestSerializer = [AFJSONRequestSerializer serializer];
[session.requestSerializer requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
[session POST:@"" parameters:@"" progress:nil success:nil failure:nil];
果不其然,这次的返回结果就正常了。
(方法二)最后在网上搜寻了一圈看到也可以使用AFURLSessionManager
来做网络请求,不过AFURLSessionManager
需要上传个NSData类型的数据。代码如下:
NSData *postData = [parameters dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:@"url" parameters:nil error:nil];
request.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPBody:postData];
[[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
NSLog(@"responseObject: %@", responseObject);
} else {
NSLog(@"error: %@, %@, %@", error, response, responseObject);
}
}] resume];至此这个问题算是解决了,也可以正常拿到后台返回的数据。
参考:https://www.cnblogs.com/wanxudong/p/6213860.html