当使用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");
}];
错误块中的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 :(得分: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视为成功,并将调用成功块。
答案 1 :(得分:2)
我想提出自己解决这个问题的方法。如果您使用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)。