2014-02-20 31 views
1

使用If-Modified-Since查詢我的webservice時,即使用Postman Rest Client,我得到的正確響應是304,內容中沒有數據。AFNetworking和304 NotModified返回錯誤

然而,當我從我的應用程序這樣做,我得到以下錯誤:

錯誤:請求失敗:不修改(304),有256

我這是如何初始化請求:

NSMutableURLRequest *request = [requestSerializer requestWithMethod:@"GET" URLString:[[NSURL URLWithString:@"myUrl" relativeToURL:[baseURL absoluteString] parameters:nil]; 

self = [self initWithRequest:request]; 

[request setValue:modifyDate forHTTPHeaderField:@"If-Modified-Since"]; 

這是我的操作:

[self setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id JSON) 
{ 
    DLog(@"Response: %@", [operation responseString]); 

    int statusCode = operation.response.statusCode; 
    if(statusCode == 304) //NotModified 
    { 
     DLog(@"This is where i want to go"); 
    } 
    success(); 
} failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
    DLog(@"ERROR RESPONSE: %@", [operation responseString]); 
    DLog(@"This is where I get"); 
}]; 

中的responseString錯誤塊是emtpy。

這是錯誤給我打印:

Printing description of error: 
Error Domain=AFNetworkingErrorDomain Code=-1011 "Request failed: not modified (304), got 256" UserInfo=0x8a7dd10 {NSErrorFailingURLKey=http://myApiUrl, AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0x8acc5e0> { URL: http://10.225.80.63/api/getAllRegionsAndCancertypes } { status code: 304, headers { 
    "Cache-Control" = "no-cache"; 
    Date = "Thu, 20 Feb 2014 10:23:10 GMT"; 
    Expires = "-1"; 
    Pragma = "no-cache"; 
    Server = "Microsoft-IIS/7.5"; 
    "X-AspNet-Version" = "4.0.30319"; 
    "X-Powered-By" = "ASP.NET"; 
} }, NSLocalizedDescription=Request failed: not modified (304), got 256} 

我缺少什麼?即使在錯誤模塊中,狀態似乎也是正確的,但爲什麼我要到達那裏呢?

謝謝!

+0

代碼304已被AFNetworking使用並且意味着(Data not Modified),那麼您可以查看緩存中的數據以獲取數據。但是,這不可能是代碼304的成功。 –

+0

所以當響應是304時應該有錯誤? – ullstrm

+0

那麼只有狀態碼200纔會進入成功塊? – ullstrm

回答

4

默認情況下AFNetworking只將200視爲成功,但有一種方法可以指定應視爲成功的狀態碼。爲此,您可以使用響應系列化,這裏是代碼

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 

AFHTTPResponseSerializer *respSerializer = [AFHTTPResponseSerializer serializer]; 
NSMutableIndexSet *responseCodes = [NSMutableIndexSet indexSet]; 
[responseCodes addIndex:200]; 
[responseCodes addIndex:304]; 
respSerializer.acceptableStatusCodes = responseCodes; 

[operation setResponseSerializer:respSerializer]; 

與此代碼AFNetworking將把304的成功,它會調用成功塊。

+0

試圖編輯它,但被拒絕。 Horray! :「respSerializer.acceptableStatusCodes = responseCodes;」 – ullstrm

+0

我已將它添加到您@Spoek中 – Sean

1

我想提出自己的解決方案。如果您使用AFNetworking 3.0和要求的singletone類AFHTTPSessionManager工作:

AFHTTPSessionManager *sessionManager = ... 
... 
NSMutableIndexSet *responseCodes = [[NSMutableIndexSet alloc] initWithIndexSet:sessionManager.responseSerializer.acceptableStatusCodes]; 
// Add code 304 in 'success list' 
[responseCodes addIndex:304]; 

sessionManager.responseSerializer.acceptableStatusCodes = responseCodes; 
... 

這種做法並不違反responseSerializer配置(如果你使用AFJSONResponseSerializer爲例)。