AFNetworking 2如何设置每个请求更新的标头

时间:2014-03-07 03:18:35

标签: ios afnetworking-2

我正在试图找到一种方法来更新为发送到我的api的每个请求生成的身份验证令牌。

我目前正在继承AFHTTPSessionManager

·H

@interface ZXHTTPSessionManager : ZXHTTPSessionManager

+ (ZXHTTPSessionManager *)sharedClient;

@end

的.m

#import "ZXHTTPSessionManager.h"

@implementation ZXHTTPSessionManager


+ (ZXHTTPSessionManager *)sharedClient
{
    static ZXHTTPSessionManager *_sharedClient = nil;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{
        NSURL *baseURL = [NSURL URLWithString:APIBASEURL];

        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        [config setHTTPAdditionalHeaders:@{@"User-Agent": @"MY APP"}];

        _sharedClient = [[ZXHTTPSessionManager alloc] initWithBaseURL:baseURL sessionConfiguration:config];
        _sharedClient.responseSerializer = [AFJSONResponseSerializer serializer];
    });

    return _sharedClient;
}

- (void)setAuthToken:(NSString *)token
{
    [[self requestSerializer] setValue:token forHTTPHeaderField:@"auth_token"];
}

@end

创建任务

NSURLSessionDataTask *task = [[ZXHTTPSessionManager sharedClient] GET:@"/post"
                            parameters:@{ @"id" : @"123"}
                               success:^(NSURLSessionDataTask *task, id responseObject) {

                               } failure:^(NSURLSessionDataTask *task, NSError *error) {

                               }];

3 个答案:

答案 0 :(得分:1)

目前没有使用AFHTTPSessionManager,但我确信它有点类似。在AFHTTPClient中,每个请求都按以下方法进行:

- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
                                  path:(NSString *)path
                            parameters:(NSDictionary *)parameters

你可以在这里修改它。或者更好的方法是使用以下方法传递从上面的方法返回的NSMutableURLRequest

- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest
                                                success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                                                failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure

您可以在子类中覆盖它,并对urlRequest标头进行更改。请注意,此方法采用NSURLRequest,因此需要创建可变版本的请求。

在对标题进行修改后调用super。

答案 1 :(得分:1)

@tiltem

谢谢,你帮助我解决了我的问题的答案。

我在文档中挖掘了更多内容,并阅读:

To change the behavior of all data task operation construction, which is also used in the GET / POST / et al. convenience methods, override dataTaskWithRequest:completionHandler:


- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
                            completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
{
    // Do custom
    return [super dataTaskWithRequest:request completionHandler:completionHandler];
}

答案 2 :(得分:0)

如果你使用AFNetworking 2.0,你可以覆盖HTTPRequestOperationWithRequest这个方法,如

#pragma mark - AFHTTPRequestOperationManager overridden methods
- (AFHTTPRequestOperation*)HTTPRequestOperationWithRequest:(NSURLRequest*)request
                                               success:(void (^)(AFHTTPRequestOperation* operation, id responseObject))success
                                               failure:(void (^)(AFHTTPRequestOperation* operation, NSError* error))failure;
{
    //Add cookie into request headers.
    NSMutableURLRequest* modifiedRequest = request.mutableCopy;
    NSMutableDictionary* modifiedHeaders = [request.allHTTPHeaderFields mutableCopy];


    [modifiedHeaders setValue:@"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36 abuMoviesDemo/1.0" forKey:@"User-Agent"];
    modifiedRequest.allHTTPHeaderFields = modifiedHeaders;

    return [super HTTPRequestOperationWithRequest:modifiedRequest success:success failure:failure];
}

如果使用AFNetworking 3.0,则设置AFHTTPSessionManager的requestSerializer变得简单。如:

- (void)modifyUserAgent
{
    [self.requestSerializer setValue:@"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36 abuMoviesDemo/1.0" forHTTPHeaderField:@"User-Agent"];
}