NSURLRequest setting the HTTP header

IphoneObjective CCocoaCocoa TouchIos

Iphone Problem Overview


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?

Iphone Solutions


Solution 1 - Iphone

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"];

Solution 2 - Iphone

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")

Solution 3 - Iphone

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

Solution 4 - Iphone

> 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)

Solution 5 - Iphone

You can add value in NSMutableURLRequest for HeaderField :

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

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

This is working for me.

Solution 6 - Iphone

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;
             

         }
     }];

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRaphaelView Question on Stackoverflow
Solution 1 - IphoneLarry HippView Answer on Stackoverflow
Solution 2 - IphoneBeslan TularovView Answer on Stackoverflow
Solution 3 - IphoneRam SView Answer on Stackoverflow
Solution 4 - IphoneUmair KhalidView Answer on Stackoverflow
Solution 5 - IphoneSaroj Kumar ojhaView Answer on Stackoverflow
Solution 6 - IphoneBinoy joseView Answer on Stackoverflow