设置后缺少 AFNetworking 请求 header

AFNetworking request header missing after being set

我正在尝试使用 AFNetworking 在 per-request 的基础上设置自定义 headers,但有时 headers 在设置后似乎会消失。下面是用于发出请求的代码...

+ (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% 的请求都按预期进行了。但是,偶尔会有一些失败并指示 header 丢失。这已通过使用 Fiddler 捕获有问题的请求并看到 headers 实际上丢失来确认。尽管如此,request.allHTTPHeaderFields 的控制台日志始终显示 header 就位。

我唯一注意到的另一件事是,通常 Fiddler 将每个请求的缓存策略报告为 "max-age=0, private, must-revalidate"。但是,每当请求丢失自定义 headers 时,它的缓存策略是 "no-cache".

这是因为您以错误的方式添加了 HTTP Header 字段。

您应该在请求之前添加它。你可以尝试这样的事情:

+ (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];

}