最近项目内需求,使用WebView加载网页,加载网页的时候需要post参数去让网页生成数据,还要在头部添加特殊标识
WebView原生的api里边有post参数的api
//post是一个byte[]
webview.postUrl(url,post) ;
添加header的Api有
//headers是一个map
webview.loadUrl(url,headers);
这两个Api只能单独使用,不能两个同时使用;
纠结了很长时间,逛玩eoe, csdn各大网站搜索无果,
最后在stackoverflow 中找到 类似的问题,并且解决,
不废话了 贴代码
public class MyWebViewClient extends WebViewClient {
@SuppressLint("NewApi")
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
//在这个函数内,可以拦截WebView内的所有url,通过拦截url进行重新封装HttpUrlConnection 将header添加进连接,post参数写入
//然后重新生成一个 WebResourceResponse
if(!TextUtils.isEmpty(params)){
String mParams = params ;
params= null;
try {
URL mUrl=new URL(url);
HttpURLConnection connection= (HttpURLConnection)mUrl.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("resource", "android");
connection.setRequestProperty("client", "clientapp");
DataOutputStream os=new DataOutputStream(connection.getOutputStream());
os.writeBytes(mParams);
os.flush();
params =null;
return new WebResourceResponse("text/html", connection.getContentEncoding(), connection.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}finally{
params =null;
}
}
return super.shouldInterceptRequest(view, url);
}
}
打完收工................