Alex Rivera | Logout

How do I insert a POST request into a UIWebView

Asked 2010-01-04T22:33:53.100
13

For a GET request I've tried this simple method:

NSString *urlAddress = @"http://example.com/";
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[uiWebViewThingy loadRequest:request];

(Although it doesn't seem to work if the request contains high UTF-8 characters. )

I want to send a POST from the iPhone.

This also give an overview for sending POST/GET requests although what I really want to do is embed the resulting web page into UIWebView. What would be the best way to go around that?

Edit
Report

2 Answers

13

You can use an NSMutableURLRequest, set the HTTP method to POST, and then load it into your UIWebView using -loadRequest.

answered 2010-01-04T23:02:38.780
2

Using loadHTMLString, feed a page to the UIWebView that has a hidden, pre-populated form, then make that page do a Javascript forms[0].submit() on loading.

EDIT: First, you collect the input into variables. Then you compose HTML like this:

NSMutableString *s = [NSMutableString stringWithCapacity:0];
[s appendString: @"<html><body onload=\"document.forms[0].submit()\">"
 "<form method=\"post\" action=\"http://someplace.com/\">"
 "<input type=\"hidden\" name=\"param1\">"];
[s appendString: Param1Value]; //It's your variable
[s appendString: @"</input></form></body></html>"];

Then you add it to the WebView:

[myWebView loadHTMLString:s baseURL:nil];

It will make the WebView load the form, then immediately submit it, thus executing a POST request to someplace.com (your URL will vary). The result will appear in the WebView.

The specifics of the form are up to you...

answered 2010-01-04T22:38:53.807

Your Answer