AFNetworking 2.0向GET请求添加标头 [英] AFNetworking 2.0 add headers to GET request

查看:373
本文介绍了AFNetworking 2.0向GET请求添加标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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

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

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

任何帮助都将不胜感激。

问候,
Mike

Any help would be appreciated.
Regards,
Mike

推荐答案

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

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

或者,如果你按照他们推荐的方法创建一个派生自 AFHTTPSessionManager 的会话管理器,那么该类可以覆盖一个方法来修改每个请求的头文件 -dataTaskWithRequest:completionHandler: 。我使用它来检查请求并根据具体情况修改标头,并且更喜欢修改序列化程序,因为它保留了该管理器中包含的网络的责任(并避免与单身人员混在一起)

Alternatively, if you follow their recommended approach of creating a session manager that derives from AFHTTPSessionManager then 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)

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

这篇关于AFNetworking 2.0向GET请求添加标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆