ios AFNetworking 2.0 向 GET 请求添加标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19466291/
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-31 02:25:49  来源:igfitidea点击:

AFNetworking 2.0 add headers to GET request

iphoneiosobjective-cafnetworkingafnetworking-2

提问by Mackey18

I've just started using AFNetworking 2.0 and I was wondering how I put in headers into a HTTP Get request. The documentation sets up a GET like this:

我刚刚开始使用 AFNetworking 2.0,我想知道如何将标头放入 HTTP Get 请求中。文档设置了这样的 GET:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo": @"bar"};
[manager POST:@"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];

But since we're not handling NSURLRequestsI'm not sure how to set HTTP Headers.

但是由于我们没有处理,NSURLRequests我不确定如何设置 HTTP 标头。

Any help would be appreciated.
Regards,
Mike

任何帮助,将不胜感激。
问候,
迈克

回答by Shaheen Ghiassy

Here's an example using AFNetworking 2.0

这是使用 AFNetworking 2.0 的示例

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:@"calvinAndHobbesRock" forHTTPHeaderField:@"X-I do what I want"];

[manager GET:@"http://localhost:3000" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

The key are the following 2 lines:

关键是以下两行:

manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:@"calvinAndHobbessRock" forHTTPHeaderField:@"X-I-do-what-I-want"];

回答by RyanR

The fantastic documentation for AFNetworking 2.0 makes this a little hard to find, but it is there. On the AFHTTPRequestSerializeris -setValue:forHTTPHeaderField:.

AFNetworking 2.0 的精彩文档让这个有点难找,但它就在那里。在AFHTTPRequestSerializer-setValue:forHTTPHeaderField:

Alternatively, if you follow their recommended approach of creating a session manager that derives from AFHTTPSessionManagerthen that class can override a method to modify headers on each request -dataTaskWithRequest:completionHandler:. I use this to inspect requests and modify headers on a case-by-case basis, and prefer it to modifying the serializer as it keeps the responsibility for networking contained in that manager (and avoids mucking with singletons)

或者,如果您按照他们推荐的方法创建派生自的会话管理器,AFHTTPSessionManager则该类可以覆盖一个方法来修改每个请求的标头-dataTaskWithRequest:completionHandler:。我使用它来逐个检查请求并修改标头,并且更喜欢它修改序列化程序,因为它保留了该管理器中包含的网络责任(并避免与单例混淆)

- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLResponse *, id, NSError *))completionHandler
{
    static NSString *deviceId;
    if(!deviceId)
    {
        deviceId = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    }

    NSMutableURLRequest *req = (NSMutableURLRequest *)request;
    // Give each request a unique ID for tracing
    NSString *reqId = [NSString stringWithFormat:@"%@+%@", deviceId, [[NSUUID UUID] UUIDString] ];
    [req setValue:reqId forHTTPHeaderField:"x-myapp-requestId"];
    return [super dataTaskWithRequest:req completionHandler:completionHandler];
}

回答by user2073541

adding response and request serializer solved my problem.

添加响应和请求序列化程序解决了我的问题。

manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];

[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

回答by Carlos Avalos

I have used this form to make an appointment with a specific header.

我已使用此表格与特定标题进行约会。

AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
[operationManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[operationManager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

[operationManager POST:url
            parameters:params
               success:^(AFHTTPRequestOperation *operation, id responseObject) {

                   if (success) {
                       success(responseObject);
                   }

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

                   NSLog(@"Error: %@", [error description]);

               }
 ];

回答by Chris

Here's what i believe to be a best option. In a singleton somewhere, configure an AFHTTPSessionManagerusing an NSURLSessionConfiguration, and then use that AFHTTPSessionManagerevery time you want to make a request.

这是我认为最好的选择。在某个地方的单例中,配置一个AFHTTPSessionManagerusing NSURLSessionConfiguration,然后在AFHTTPSessionManager每次要发出请求时使用它。

NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.HTTPAdditionalHeaders = @{@"Accepts": @"application/json"};

mySingletonSessionManager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:kMyBaseUrl] sessionConfiguration:config];

回答by Serge Pedroza

I did this...for those that are passing token

我这样做了......对于那些传递令牌的人

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

回答by Evana

Use the following code to put any type of header value:

使用以下代码放置任何类型的标头值:

[[FRHTTPReqManager sharedManager].requestSerializer setValue:value forHTTPHeaderField:key];