webview post传参用法

iOS WebView Post传参用法(注意URLEncoding编码)

UIWebView
WebView UrlEncoding陈年老坑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// post请求传参数
UIWebView *webView = [[UIWebView alloc] initWithFrame:[UIScreen mainScreen].bounds];

// 将UIWebView添加到当前View
[self.view addSubview:webView];

// 设置访问的URL
NSURL *url = [NSURL URLWithString:@"http://www.example.com"];
NSURL *url = [NSURL URLWithString: @"需要填写自己的URL"];
NSString *body = [NSString stringWithFormat: @"arg1=%@&arg2=%@", @"val1",@"val2"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url];
body = [body stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"#%<>[\\]^`{|}\"]+"].invertedSet];//切记要注意urlEnding编码 这个是坑啊
[request setHTTPMethod: @"POST"];
[request setHTTPBody: [body dataUsingEncoding: NSUTF8StringEncoding]];
[webView loadRequest: request];

WKWebview

post请求提交参数 存在参数不能提交的问题 附上解决问题链接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/// WKWebview代理方法
/* 1.在发送请求之前,决定是否跳转 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler;

/* 2.页面开始加载 */
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation;

/* 3.在收到服务器的响应头,根据response相关信息,决定是否跳转。 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler;

/* 4.开始获取到网页内容时返回,需要注入JS,在这里添加 */
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation;

/* 5.页面加载完成之后调用 */
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation;
/* error - 页面加载失败时调用 */
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation;
/* 其他 - 处理服务器重定向Redirect */
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation;