How to add custom header to AFNetworking on a JSONRequestOperation
Asked Answered
D

4

19

Hi, I have the following code accessing a 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.

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

Daltondaltonism answered 28/2, 2013 at 16:50 Comment(0)
C
30

Use AFHTTPClient or subclass it!

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

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

You can check the documentation

Calen answered 28/2, 2013 at 16:55 Comment(1)
For AFN version 2.x and AFHTTPRequestOperationManager, you could do it like this: [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];Labium
C
28
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];

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

[AFJSONRequestOperation JSONRequestOperationWithRequest: request ...]
Crenshaw answered 28/2, 2013 at 16:58 Comment(3)
I think its the opposite right? X-USER-TOKEN on HTTPHeaderFieldDaltondaltonism
maybe ;). I don't know if X-USER-TOKEN was the variable value or the field nameCrenshaw
Now its addValue, and not setValue :)Pizzeria
R
8

I did this :)

[manager.requestSerializer setValue:[NSString stringWithFormat:@"Token token=\"%@\"", _userObj.oAuth] forHTTPHeaderField:@"Authorization"];
Riproaring answered 21/5, 2015 at 3:28 Comment(1)
Getting an error No Known instance method for selector 'setValue:forHTTPHeaderField'Decompress
A
3

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

 [[HTTPClient sharedHTTPClient].requestSerializer setValue:YOUR_KEY forHTTPHeaderField:@"X-Register"];
Agretha answered 24/9, 2014 at 23:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.