AFNetworking 2.0 Request w. Custom Header

12,687

Under AFHTTPRequestOperationManager you will notice a property called requestSerializer. This is of type AFHTTPRequestSerializer, and requests made through the HTTP manager are constructed with the headers specified by this object.

So, try this:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

[manager.requestSerializer setValue:@"SomeValue" forHTTPHeaderField:@"SomeHeaderField"]

//Make your requests

You can read the headers dictionary from the request serializer as follows:

manager.requestSerializer.HTTPRequestHeaders

Note that once you set a header this way, it will be used for all other operations!

Share:
12,687
ChuckKelly
Author by

ChuckKelly

Mobile developer & long time graphic designer with evil plans to take over the universe one key stoke at a time. Links: www.WhoisChuckKelly.com -Portfolio of some of my older design work , personal bio & current skill sets

Updated on June 08, 2022

Comments

  • ChuckKelly
    ChuckKelly about 2 years

    Ive tried to avoid asking such a newb question on here, but im a Android dev learning IOS and I cant figure out for the life of me how to add a simple header to my post requests using AFNetworking 2.0. Below is my code so far which works if i want to make a request that doesnt require a header.Could anyone show me via adding to my snippet or providing a alternate one that does this? I came across this tut: http://www.raywenderlich.com/30445 that shows how to add a header under the "A RESTful Class" heading , but its for afnetworking 1.0 and is now depreciated as far as i can tell.

        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        NSDictionary *parameters = @{@"uid": @"1"};
        AFHT
        [manager POST:@"http://myface.com/api/profile/format/json" parameters:parameters  success:^(AFHTTPRequestOperation *operation, id responseObject) {
            //NSLog(@"JSON: %@", responseObject);
    
            self.feedArray = [responseObject objectForKey:@"feed"];
    
            [self.tableView reloadData];
    
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Error: %@", error);
        } ];
    }
    
  • AbcAeffchen
    AbcAeffchen almost 10 years
    Your answer should contains an explanation of your code and a description how it solves the problem.
  • OhadM
    OhadM over 8 years