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

最近项目内需求,使用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);
        }
    }
打完收工................ 


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值