HTTP POST from iOS

This post shares the code to do a simple HTTP POST from iOS.

NSString *post = [NSString stringWithFormat:@"key1=%@&key2=%@",value1,value2];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
NSString *urlString = @"http://someurl";
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

  1. No comments yet.

  1. No trackbacks yet.