14

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.

Black Frog
  • 11,595
  • 1
  • 35
  • 66
Mayur Birari
  • 5,837
  • 8
  • 34
  • 61

1 Answers1

23

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];
Mayur Birari
  • 5,837
  • 8
  • 34
  • 61
  • Adding custum Key-Value in NSMutableURLRequest does not work for HTTPS URLs... Any idea?? – DShah Sep 16 '13 at 12:43
  • Urls are HTTP or HTTPS it does not matter. NSMutableRequest sends attribute in either case. Have you handle authentication delegate for HTTPS service? – Mayur Birari Sep 17 '13 at 11:43
  • You claim to be setting content type to JSON and yet to set it to xml? You have to set it to `application/json` – Houman Sep 22 '14 at 11:57
  • hey @MayurBirari can you answer this too: http://stackoverflow.com/questions/40342728/sending-httpheaderfield-for-nsurlrequest-in-afmultipartformdata – Chaudhry Talha Oct 31 '16 at 14:05