AFNetworkingErrorDomain 錯誤解決方法

徐明清發表於2014-09-27

首先我們來看一下錯誤資訊:

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];
}

部落格寫的較倉促,所以程式碼沒有封裝的很細,這裡僅供大家參考.

相關文章