陈斌彬的技术博客

Stay foolish,stay hungry

AFNetWorking Error Domain

Error Domain=com.alamofire.error.serialization.response Code=-1016 “Request failed: unacceptable con

在发送请求后,NSURLSessionDataTask一直报错

Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/html"  

经过一番网上排查,网上有人说是AF2.0本身的问题,解析格式不全,所以需要在AF的源文件AFURLResponseSerialization.m中修改代码就能解决: 修改文件223行处

self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil nil];  

为:

self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil nil];  

即可,但是AF还在持续更新的类库,不宜随意修改,特别是在用了CocoaPods之后,如果之后更新库,此类错误又会重复出现,随后发现acceptableContentTypes是一个开放的属性,既然这样,就证明acceptableContentTypes可以在外部被修改,所以可以在初始化HttpClient单例的时候改变这一值:

- (instancetype)initWithBaseURL:(NSURL *)url {  
    if (self = [super initWithBaseURL:url]) {  

        self.responseSerializer = [AFJSONResponseSerializer serializer];  
        self.requestSerializer.timeoutInterval = TimeoutInterval;  
        self.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil nil];  
        [self setHTTPHeader];  // 可在此处设置Http头信息  
    }  
    return self;  
}