AFNetworkingErrorDomain 错误解决方法
首先我们来看一下错误信息:
Error Domain=AFNetworkingErrorDomain Code=-1011 "Expected status code in (200-299), got 406" { status code: 406,headers { "Content-Language" = en; "Content-Length" = 1110; "Content-Type" = "text/html;charset=utf-8"; Date = "Sat, 27 Sep 2014 05:29:13 GMT"; Server = "Apache-Coyote/1.1"; } }
相信很多小伙伴会遇到这种问题,又找不到方法解决.然后今天的项目再次出现了这个问题,因为之前遇到过类似问题,是通过搜索"text/"找到下面这段代码:
+ (NSSet *)acceptableContentTypes { return [NSSet setWithObjects:@"text/html", @"text/plain", @"application/json", @"text/json", @"text/javascript", nil]; }
在中间插入@"text/html",基本上问题就解决了,但是这次却没有.我来来回回看了好多变代码,也测试了好几次,最后发现了问题,原来是我在封装请求方法时没有加入请求头协议:
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]]; [httpClient setDefaultHeader:@"Accept" value:@"application/json"];
加上上面俩句后问题马上得到解决.
最后总结一下:一般遇到这种情况,先查看
+ (NSSet *)acceptableContentTypes { return [NSSet setWithObjects:@"text/html", @"text/plain", @"application/json", @"text/json", @"text/javascript", nil]; }
这个方法中有没有包含服务器返回的数据格式,如果没有就加上.然后执行代码测试是否通过,如果未通过,再看一下你封装的请求方法中是否没有加入请求头协议.下面是我的完整的封装GET和POST请求方法代码,给大家参考一下:
+ (void)postWithBaseURL:(NSString *)baseURL path:(NSString *)path params:(NSDictionary *)params success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure { // 封装请求 AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:baseURL]]; [client registerHTTPOperationClass:[AFJSONRequestOperation class]]; [client setDefaultHeader:@"Accept" value:@"application/json"]; NSURLRequest *post = [client requestWithMethod:@"POST" path:path parameters:params]; // 创建AFJSONRequestOperation对象 NSOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:post success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { success(JSON); } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) { failure(error); }]; // 发送请求 [operation start]; } +(void)getWithBaseURL:(NSString *)baseURL path:(NSString *)path params:(NSDictionary *)params success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure { // 封装请求 AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:baseURL]]; [client registerHTTPOperationClass:[AFJSONRequestOperation class]]; [client setDefaultHeader:@"Accept" value:@"application/json"]; NSURLRequest *post = [client requestWithMethod:@"GET" path:path parameters:params]; // 创建AFJSONRequestOperation对象 NSOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:post success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { success(JSON); } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) { failure(error); }]; // 发送请求 [operation start]; }
posted on 2015-08-13 13:33 ZhaoHanjun 阅读(474) 评论(0) 编辑 收藏 举报