使用POST参数通过UIWebView加载网页

是否有可能通过POST参数通过UIWebView加载页面? 我可能只是加载一个embedded式的forms与参数,并填写他们与JavaScript和强制提交,但有更清洁,更快的方式?

谢谢!

创buildPOST URLRequest并使用它来填充webView

NSURL *url = [NSURL URLWithString: @"http://your_url.com"]; NSString *body = [NSString stringWithFormat: @"arg1=%@&arg2=%@", @"val1",@"val2"]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url]; [request setHTTPMethod: @"POST"]; [request setHTTPBody: [body dataUsingEncoding: NSUTF8StringEncoding]]; [webView loadRequest: request]; 

对于Swift

以下是内容types为x-www-form-urlencoded的web视图POST调用示例。

  let url = NSURL (string: "https://www.google.com") let request = NSMutableURLRequest(URL: url!) request.HTTPMethod = "POST" request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") let post: String = "sourceId=44574fdsf01e-e4da-4e8c-a897-17722d00e1fe&sourceType=abc" let postData: NSData = post.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: true)! request.HTTPBody = postData webView.loadRequest(request) 

您需要更改其他内容types的postData。

oxigen的答案只是略有改变。 使用时:

  NSString *theURL = @"http://your_url.com/sub"; ...//and later [request setURL:[NSURL URLWithString:theURL]]; 

它不起作用,既不是GET或POST请求,当它添加了一个结束斜线的URL它的工作。

  NSString *theURL = @"http://your_url.com/sub/"; 

这是@ 2ank3th的修改答案,适用于swift 3:

  let url = NSURL (string: "https://www.google.com") let request = NSMutableURLRequest(url: url! as URL) request.httpMethod = "POST" request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") let post: String = "sourceId=44574fdsf01e-e4da-4e8c-a897-17722d00e1fe&sourceType=abc" let postData: NSData = post.data(using: String.Encoding.ascii, allowLossyConversion: true)! as NSData request.httpBody = postData as Data webView.loadRequest(request as URLRequest)