AFNetworking和304 NotModified返回错误



当使用Postman Rest Client查询我的Web服务时,使用If-Modified-Since,我得到了304的正确响应,内容中没有数据。

但是,当我从我的应用程序执行此操作时,我收到以下错误:

错误:请求失败:未修改 (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");
 }];

错误块中的响应字符串是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}

我错过了什么?即使在错误块中,状态似乎也是正确的,但是为什么我能到达那里呢?

谢谢!

默认情况下,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视为成功,并将调用成功块。

我想

提出我自己的解决这个问题的变体。如果您使用 AFNetworking 3.0 并在请求的单调类中使用 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

)。

最新更新