在AFNetworking请求中忽略If-Modified-Since或If-None-Match标头

and*_*ers 3 caching afnetworking

我正在使用AFNetworking 1.3.3从Amazon S3获取静态JSON文件.如果我要求使用谷歌浏览这些文件和检查头,它发出了一个If-Modified-SinceIf-None-MatchHTTP头中的请求,你回来一个漂亮的304响应预期.

但是,当我使用AFNetworking发出相同的请求,发送相同If-Modified-Since和相同的If-None-Match标题时,我每次都会获得200,即使我知道内容未被修改.它似乎忽略了我发送的额外标题.

这是我的代码:

NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:feedUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];

[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

if (feed.remoteLastModified != nil) {
    // In real life I use the last modified header returned by the request
    [request setValue:@"Tue, 10 Dec 2013 07:15:50 GMT" forHTTPHeaderField:@"If-Modified-Since"];
}

if (feed.remoteETag.length > 0) {
    NSLog(@"If-None-Match: %@", feed.remoteETag);
    [request setValue:feed.remoteETag forHTTPHeaderField:@"If-None-Match"];
}

NSLog(@"headers: %@", request.allHTTPHeaderFields);

AFJSONRequestOperation* operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest* request, NSHTTPURLResponse* response, id JSON) {

    NSLog(@"Status code: %d", response.statusCode);        

} failure:^(NSURLRequest* request, NSHTTPURLResponse* response, NSError* error, id JSON) {
    if (response.statusCode != 304) {
        NSLog(@"There was an error: %@", [error userInfo]);
    } else {
        NSLog(@"Not modified");
    }
}];

[operation start];
Run Code Online (Sandbox Code Playgroud)

and*_*ers 6

问题是使用的缓存策略 - NSURLRequestUseProtocolCachePolicyNSURLCache将在后台进行自己的缓存,并将透明地返回原始200响应的缓存结果.

如果您确实希望自己进行缓存,请使用NSURLRequestReloadIgnoringLocalCacheData缓存策略.这并不意味着它会忽略您的缓存标头(我最初假设) - 它只是意味着NSURLCache将忽略它自己的本地缓存.

然而,自己做这件事并重新发明轮子可能是错误的方法!