如何在JSONRequestOperation上向AFNetworking添加自定义标头

时间:2013-02-28 16:50:40

标签: ios objective-c json afnetworking nsurlrequest

嗨,我有以下代码访问网址:

NSString * stringURL = [NSString stringWithFormat:@"%@/%@/someAPI", kSERVICE_URL, kSERVICE_VERSION];
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:stringURL]];

AFJSONRequestOperation * operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    completionHandler(JSON, nil);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
    completionHandler(nil, error);
}];

但我想将用户令牌作为HEADER上的参数传递,例如X-USER-TOKEN

无法在AFNetworking documentation找到它,我应该更改操作类型吗?

4 个答案:

答案 0 :(得分:30)

使用AFHTTPClient或将其子类化!

您可以使用-setDefaultHeader:value:设置默认标头,如下所示:

[self setDefaultHeader:@"X-USER-TOKEN" value:userToken];

您可以查看documentation

答案 1 :(得分:28)

NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];

[request setValue: @"X-USER-TOKEN"  forHTTPHeaderField:@"< clientToken >"];

[AFJSONRequestOperation JSONRequestOperationWithRequest: request ...]

答案 2 :(得分:8)

我这样做了:)

[manager.requestSerializer setValue:[NSString stringWithFormat:@"Token token=\"%@\"", _userObj.oAuth] forHTTPHeaderField:@"Authorization"];

答案 3 :(得分:3)

如果你有一个抽象层,让我们说APIManager, 那么你应该在特定方法中执行以下操作

 [[HTTPClient sharedHTTPClient].requestSerializer setValue:YOUR_KEY forHTTPHeaderField:@"X-Register"];