NSURLConnection synchronous request on https

Anis picture Anis · Jan 6, 2011 · Viewed 36.1k times · Source

Can anyone tell me the way how I can make a synchronous call to the https server? I am able to do asynchronous request on https server using following delegate methods.

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace

and

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge

but I need to do synchronous.

Answer

Snehal picture Snehal · Jan 6, 2011

//Encoding the request

NSData *postData = [xmlText dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

**//Calculating length of request**
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:requestUrlString]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/xml" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse* response;
NSError* error = nil;

//Capturing server response
NSData* result = [NSURLConnection sendSynchronousRequest:request  returningResponse:&response error:&error];