Sunday, January 31, 2010

How to make a POST request with iPhone sdk

To make a web request with the iPhone is very simple. The following code is an example of how you can do it. If you need to pass some variables to the server, just use the lines that are in bold.

NSURL *url = [NSURL URLWithString:@"http://www.google.com.br"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
NSData *requestBody = [@"username:x&password:y" dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:requestBody];
NSURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSString *responseString = [[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] autorelease];

 Ready. The variable responseString will have all the text that the server has returned.

4 comments: