AFNetworkingErrorDomain 錯誤解決方法

首先咱們來看一下錯誤信息:

Error Domain=AFNetworkingErrorDomain Code=-1011 "Expected status code in (200-299), got 406" javascript

{ status code: 406,headers {html

"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";
} }
java

相信不少小夥伴會遇到這種問題,又找不到方法解決.而後今天的項目再次出現了這個問題,由於以前遇到過相似問題,是經過搜索"text/"找到下面這段代碼:

+ (NSSet *)acceptableContentTypesjson

{
  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 *)acceptableContentTypesapp

{
  return [NSSet setWithObjects:@"text/html", @"text/plain", @"application/json", @"text/json", @"text/javascript", nil];
}post

這個方法中有沒有包含服務器返回的數據格式,若是沒有就加上.而後執行代碼測試是否經過,若是未經過,再看一下你封裝的請求方法中是否沒有加入請求頭協議.下面是個人完整的封裝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];
}spa

相關文章
相關標籤/搜索