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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15141115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 22:29:44  来源:igfitidea点击:

How to add custom header to AFNetworking on a JSONRequestOperation

iosobjective-cjsonafnetworkingnsurlrequest

提问by Andre Cytryn

Hi, I have the following code accessing a URL:

嗨,我有以下访问 URL 的代码:

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);
}];

But I want to pass the user token as a parameter on HEADER, like X-USER-TOKEN.

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

Cant find it on AFNetworking documentation, should I change the operation type?

在 上找不到AFNetworking documentation,我应该更改操作类型吗?

回答by Moxy

Use AFHTTPClientor subclass it!

使用AFHTTPClient或子类化它!

You can set default headers with -setDefaultHeader:value:like this :

您可以-setDefaultHeader:value:像这样设置默认标题:

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

You can check the documentation

您可以查看文档

回答by Mr Bonjour

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

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

[AFJSONRequestOperation JSONRequestOperationWithRequest: request ...]

回答by Serge Pedroza

I did this :)

我这样做了:)

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

回答by Vladimir Stazhilov

If you have a layer of abstraction, let's say APIManager, then you should do the following inside a particular method

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

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