是否可以通过带有POST参数的UIWebView加载页面?我可能只是加载带有参数的嵌入表单并用javascript填充它们并强制提交,但是有更清洁和更快的方法吗?
谢谢!
创建POST 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];
以下是内容类型为x-www-form-urlencoded的Web视图POST调用示例.
您需要更改其他内容类型的postData.
对于Swift 3
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)
let url = URL (string: "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: Data = post.data(using: String.Encoding.ascii, allowLossyConversion: true)! request.httpBody = postData webView.load(request as URLRequest)
来自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/";