87

I need to set the HTTP header for a request. In the documentation for the NSURLRequest class I didn't find anything regarding the HTTP header. How can I set the HTTP header to contain custom data?

Raphael
  • 7,972
  • 14
  • 62
  • 83

6 Answers6

186

You need to use a NSMutableURLRequest

NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] initWithURL:url]
                                autorelease];

[request setValue:VALUE forHTTPHeaderField:@"Field You Want To Set"];

or to add a header:

[request addValue:VALUE forHTTPHeaderField:@"Field You Want To Set"];
Cœur
  • 37,241
  • 25
  • 195
  • 267
Larry Hipp
  • 6,205
  • 3
  • 26
  • 31
11

for Swift

let url: NSURL = NSURL(string: APIBaseURL + "&login=1951&pass=1234")!
var params = ["login":"1951", "pass":"1234"]
request = NSMutableURLRequest(URL:url)
request.HTTPMethod = "POST"
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
Beslan Tularov
  • 3,111
  • 1
  • 21
  • 34
  • I'm using similar kind of code to make a request, but it's returning **nil** data. I tried to what's wrong and only thing i could come up was the response value coming back has different value for "Content-Type" as opposed to what i'm trying to append in the beginning of code. `request.setValue("Some value", forHTTPHeaderField: "Content-Type")` is this working for you? – Sashi Apr 10 '15 at 21:21
  • try this header request.addValue("text/html", forHTTPHeaderField: "Content-Type") – Beslan Tularov Apr 11 '15 at 00:16
  • I tried that as well, but it did not work. Finally using myParameters.dataUsingEncoding worked for me, i was using something else that's the reason i think it wasn't working. Thanks for the help. – Sashi Apr 13 '15 at 17:10
6
 NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];

[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"your value" forHTTPHeaderField:@"for key"];//change this according to your need.
[request setHTTPBody:postData];
Ram S
  • 793
  • 12
  • 21
  • 2
    You should probably add some explanation for the code you have posted. – MasterAM Dec 24 '13 at 13:44
  • What does setValue:@"application/x-www-form-urlencoded" mean, is it sth custom? – Dilara Albayrak Mar 07 '16 at 13:28
  • In the case of limited support for POST in the HTTP client software where pure data cannot be submitted in the HTTP message body, RESTfm is able to handle data encoded in either application/x-www-form-urlencoded or multipart/form-data formats. Note: The application/x-www-form-urlencoded and multipart/form-data formats are only applicable to the HTTP POST method Note 2: This format uses the same 'URL encoding' scheme as required for GET query string parameters as described here. Advantages Support for larger data size than what is possible using a GET query string. – Ram S Mar 08 '16 at 04:30
  • Refer this link for more detail http://www.restfm.com/restfm-manual/web-api-reference-documentation/submitting-data/applicationx-www-form-urlencoded-and – Ram S Mar 08 '16 at 04:30
2

I know its late but may help others , For SWIFT 3.0

let url = NSURL(string: "http://www.yourwebsite.com")
    let mutAbleRequest = NSMutableURLRequest(URL: url!)
    mutAbleRequest.setValue("YOUR_HEADER_VALUE", forHTTPHeaderField:"YOUR_HEADER_NAME")
    myWebView.loadRequest(mutAbleRequest)
Umair Khalid
  • 2,259
  • 1
  • 21
  • 28
0

You can add value in NSMutableURLRequest for HeaderField :

NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];

[request setValue:VALUE forHTTPHeaderField:@"cookie"];

This is working for me.

Noor
  • 2,071
  • 19
  • 28
Saroj Kumar ojha
  • 485
  • 4
  • 15
0

Sample Code

 - (void)reqUserBalance:(NSString*)reward_scheme_id id:(NSString*)user_id success:(void (^)(id responseObject))success failure:(void (^)(id responseObject))failure{

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@reward/%@/user/%@/balance",URL_SERVER,reward_scheme_id,user_id]];
    NSLog(@"%@",url);
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];

    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"true" forHTTPHeaderField:@"Bypass"];

    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response,
                                               NSData *data, NSError *connectionError)
     {
                         options:kNilOptions error:NULL];

         if (data.length > 0 && connectionError == nil)
         {
             NSDictionary * userPoints = [NSJSONSerialization JSONObjectWithData:data
                                                                      options:0
                                                                        error:NULL];

             NSString * points = [[userPoints objectForKey:@"points"] stringValue];
             NSLog(@"%@",points);
             [SecuritySetting sharedInstance].usearAvailablePoints = points;


         }
     }];

}
Binoy jose
  • 461
  • 4
  • 9