我正在尝试使用AFNetworking在每个请求的基础上设置自定义标头,但有时候标头在设置后似乎会消失。以下是用于提出请求的代码......
+ (void) getWithURI: (NSString*) uri header: (NSDictionary*) header success: (NSString*) successCallback failure: (NSString*)errorCallback dispatch: (NSString*)dispatchedId
{
createManagerInstance();
AFHTTPRequestOperation* operation = [manager GET:uri
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
[RestWrapper succeededWithJson:operation.responseString dispatchedId:dispatchedId successCallback:successCallback];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[RestWrapper failedWithJson:operation.responseString dispatchedId:dispatchedId errorCallback:errorCallback];
}];
NSMutableURLRequest* request = (NSMutableURLRequest*)operation.request;
for (NSString* key in header)
{
if([request valueForHTTPHeaderField:key] != nil)
{
[request setValue:header[key] forHTTPHeaderField:key];
}
else
{
[request addValue:header[key] forHTTPHeaderField:key];
}
}
NSLog(@"Headers: %@", request.allHTTPHeaderFields);
[operation start];
}
对于95%的请求,他们按预期进行。但是,偶尔会有一些失败并指示标题丢失。通过使用Fiddler捕获有问题的请求并看到标题实际上已丢失,已经证实了这一点。尽管如此,request.allHTTPHeaderFields
的控制台日志始终显示标题。
我注意到的另一件事是,一般来说,Fiddler会为每个请求报告缓存策略为“max-age = 0,private,must-revalidate”。但是,每当请求丢失自定义标头时,它的缓存策略就是“无缓存”。
答案 0 :(得分:1)
这是因为您以错误的方式添加HTTP标头字段。
您应该在请求之前添加它。你可以尝试这样的事情:
+ (void) getWithURI: (NSString*) uri header: (NSDictionary*) header success: (NSString*) successCallback failure: (NSString*)errorCallback dispatch: (NSString*)dispatchedId{
createManagerInstance();
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:header[key] forHTTPHeaderField:key];
AFHTTPRequestOperation* operation = [manager GET:uri
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
[RestWrapper succeededWithJson:operation.responseString dispatchedId:dispatchedId successCallback:successCallback];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[RestWrapper failedWithJson:operation.responseString dispatchedId:dispatchedId errorCallback:errorCallback];
}];
[operation start];
}