用AFN网络请求遇到的bug

作为iOS攻城狮都知道,网络请求有一个著名的框架,那就是AFNetWorking,当发起网络请求时,我遇到了一个这样bug


请求失败--Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/plain" UserInfo={com.alamofire.serialization.response.error.response= { URL: https://api.weibo.com/oauth2/access_token } { status code: 200, headers {
"Cache-Control" = "no-cache";
"Content-Length" = 111;
"Content-Type" = "text/plain;charset=UTF-8";
Date = "Sun, 16 Jul 2017 05:45:50 GMT";
Expires = "Thu, 01 Jan 1970 00:00:00 GMT";
Pragma = "No-cache";
Server = "nginx/1.6.1";
} },

分析
unacceptable content-type: text/plain 不接受内容类型,换句话来说AFN不支持解析这种格式,

那怎么解决的呢?AFNetworking为什么能够解析服务器返回的东西呢?

因为manager有一个responseSerializer属性.它只设置了一些固定的解析格式.其中不包含text/plain这种数据的格式.因为解析报错了.

我们来看一下AFNetworking解析格式的底层:
self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];
没有后台提供的格式:text/plain,
那么,我们自己去修改,现在我发个gif图看具体如何操作

用AFN网络请求遇到的bug_第1张图片
解决content-typebug.gif

打印结果如下

f1326ddff76840101624cc777012c819&from=844b&vit=fps https://m.baidu.com/?code=f1326ddff76840101624cc777012c819&from=844b&vit=fps
2017-07-16 14:56:11.045 weibo[6532:292589] 请求成功--{
"access_token" = "2.00TP4yAG0HVdgt7874226d93SnuPeD";
"expires_in" = 129834;
"remind_in" = 129834;
uid = 5511186043;
}

你可能感兴趣的:(用AFN网络请求遇到的bug)