AFHTTPRequestOperationManager的操作无法获取标题

时间:2014-08-29 18:21:06

标签: ios afnetworking afnetworking-2

我正在使用以下代码来设置我的操作管理器:

requestSerializerJson = [AFJSONRequestSerializer serializer];
[requestSerializerJson setValue:[taskHandler getBranchesApiConstantForName:@"header_value_content_type"] forHTTPHeaderField:[taskHandler getBranchesApiConstantForName:@"header_name_content_type"]];
[requestSerializerJson setValue:[taskHandler getBranchesApiConstantForName:@"header_value_api_key"] forHTTPHeaderField:[taskHandler getBranchesApiConstantForName:@"header_name_api_key"]];

httpRequestOperationManager = [AFHTTPRequestOperationManager manager];
httpRequestOperationManager.requestSerializer = requestSerializerJson;
httpRequestOperationManager.responseSerializer = [AFJSONResponseSerializer serializer];
httpRequestOperationManager.operationQueue = [[NSOperationQueue alloc] init];
httpRequestOperationManager.operationQueue.maxConcurrentOperationCount = 1;

然后,我有一个方法可以下载多个JSON字符串:

- (void)downloadBranches {

    NSLog(@"Test %@", httpRequestOperationManager.requestSerializer.HTTPMethodsEncodingParametersInURI);

    for (NSString *branchUuid in taskHandler.addedBranchesUuids) {

        NSString *urlString = [NSString stringWithFormat:@"%@%@%@", urlBase, [taskHandler getBranchesApiConstantForName:@"getbranch_suffix"], branchUuid];
        NSURL *URL = [NSURL URLWithString:urlString];
        NSURLRequest *request = [NSURLRequest requestWithURL:URL];

        NSLog(@"Test %@", request.allHTTPHeaderFields);

        AFHTTPRequestOperation *op = [httpRequestOperationManager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {

            NSLog(@"JSON: %@", responseObject);

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

            NSLog(@"Error: %@", error);
        }];
        op.responseSerializer = [AFJSONResponseSerializer serializer];

        [httpRequestOperationManager.operationQueue addOperation:op];
    }
}

执行了所有操作,但是我从服务器收到一条消息,说明我没有提供身份验证密钥。

我专门在第3行设置了它 - requestSerializerJson然后添加到httpRequestOperationManager,所以所有请求都应该使用标题。

我添加了一个NSLog来打印request.allHTTPHeaderFields,但它说“(null)”。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

downloadBranches通过手动构建NSURLRequest完全绕过了序列化程序。序列化器的重点是为你做这件事。

您需要在序列化程序上调用requestWithMethod:URLString:parameters:,这将返回带有您想要的标题的NSURLRequest

或者只是在GET:…循环中使用操作管理器的for方法;你的用例看起来根本不需要其它东西。