Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Http header Fields in Objective-C?

I want to call web service in Objetive C which returning xml data and I have to pass some information in header to the server, just like in javascript we can do it using jquery,

x.setRequestHeader('key','value');

where x is the xmlHttpRequest Object. How we can pass the header data in NSConnection class, I used google but havent find out good solution. please help me.

like image 575
Mayur Birari Avatar asked Feb 25 '11 10:02

Mayur Birari


1 Answers

You can pass the information in header using NSMutableURLRequest class and then call the NSURLConnection class(it will call the connection delegate).

see the following code,


NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:[myServerUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]
                                                        cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                    timeoutInterval:60.0];
//do post request for parameter passing 
[theRequest setHTTPMethod:@"POST"];

//set the content type to JSON
[theRequest setValue:@"xml" forHTTPHeaderField:@"Content-Type"];

//passing key as a http header request 
[theRequest addValue:@"value1" forHTTPHeaderField:@"key1"];

//passing key as a http header request
[theRequest addValue:@"value2" forHTTPHeaderField:@"key2"];

NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

if( theConnection )
{
    webData = [[NSMutableData data] retain];
}
else
{
    NSLog(@"theConnection is NULL");
}

[theConnection release];
like image 50
Mayur Birari Avatar answered Sep 28 '22 02:09

Mayur Birari