WebView内使用post加载url并添加header

来源:互联网 发布:常熟淘宝开店 编辑:程序博客网 时间:2024/06/07 07:16

最近项目内需求,使用WebView加载网页,加载网页的时候需要post参数去让网页生成数据,还要在头部添加特殊标识

 WebView原生的api里边有post参数的api

//post是一个byte[]  webview.postUrl(url,post) ;

添加header的Api有

//headers是一个mapwebview.loadUrl(url,headers);

这两个Api只能单独使用,不能两个同时使用;


纠结了很长时间,逛玩eoe, csdn各大网站搜索无果,


最后在stackoverflow 中找到 类似的问题,并且解决,


不废话了  贴代码


public class MyWebViewClient extends WebViewClient {        @SuppressLint("NewApi")        @Override        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {            <pre name="code" class="java" style="font-size:12px; line-height: 16px; font-family: arial, sans-serif; white-space: nowrap;">              //在这个函数内,可以拦截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); }


打完收工................


0 0