Load a POST request into an UIWebView in iOS

To load a POST request into an UIWebView we use the method “loadRequest” of the UIWebView class. The key is creating the POST request.

To create a POST request you need to create the content body and append it to the request, so use the NSMutableURLRequest class instead of the NSURLRequest class that is usually used to create GET requests. In the request header, add POST as the selected Http method.

// POST data
NSString *content = [NSString stringWithFormat:
   @"param1=%@&param2=%@", value1, value2];

NSMutableData *body = [NSMutableData data];
[body appendData:
   [content dataUsingEncoding:NSUTF8StringEncoding]];

// Create request
NSMutableURLRequest *request = [[NSMutableURLRequest new] autorelease];
[request setURL:[NSURL URLWithString: 
    @"http://www.belencruz.com/exampleURL"]];

// Headers
[request setHTTPMethod:@"POST"];
NSString *postLength = [NSString stringWithFormat:@"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

// Append body
[request setHTTPBody:body];

// Load into UIWebView
[webView loadRequest:request];
Share Button

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload the CAPTCHA.