android WebView拦截URL请求添加Header及遇到的问题

WebView加载url,如果只需在初始加载的时候添加Header,那么比较简单,只需要这么写即可:

Map<String, String> header = new HashMap<>();
header.put("headkey", "value");
mWebView.loadUrl(url, header);

有些情况下,要求每个页面都要做Header验证,那么就要重写WebViewClient的shouldInterceptRequest方法了:

    private WebViewClient mWebViewClient = new WebViewClient() {

        // Handle API until level 21
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            //API 21以下,此处不考虑兼容性
            return super.shouldInterceptRequest(view, url);
        }

        // Handle API 21+
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            String url = request.getUrl().toString();
            return getNewResponse(url, request.getRequestHeaders());
        }

        private WebResourceResponse getNewResponse(String url, Map<String, String> headers) {

            try {
                OkHttpClient httpClient = new OkHttpClient();

                Request.Builder builder = new Request.Builder()
                        .url(url.trim())
                        .addHeader("abc", "zhe-shi-wo-tian-jia-de");

                Set<String> keySet = headers.keySet();
                for (String key : keySet) {
                    builder.addHeader(key, headers.get(key));
                }

                Request request = builder.build();

                final Response response = httpClient.newCall(request).execute();

                String conentType = response.header("Content-Type", response.body().contentType().type());
                String temp = conentType.toLowerCase();
                if (temp.contains("charset=utf-8")) {
                    conentType = conentType.replaceAll("(?i)" + "charset=utf-8", "");//不区分大小写的替换
                }
                if (conentType.contains(";")) {
                    conentType = conentType.replaceAll(";", "");
                    conentType = conentType.trim();
                }

                return new WebResourceResponse(
                        conentType,
                        response.header("Content-Encoding", "utf-8"),
                        response.body().byteStream()
                );

            } catch (Exception e) {
                return null;
            }

        }
    };

简单说明下,这个方法有两个重载方法,一个是android api21以下版本的,就不去考虑兼容了,这里只做保留。重新请求用的是okhttp3框架,导入:implementation 'com.squareup.okhttp3:okhttp:3.3.0',可以看到,每次请求我们都插入了自己的Header:addHeader("abc", "zhe-shi-wo-tian-jia-de")。可能有人会注意到,设置contentType的时候把charset=utf-8去掉了,这是因为如果不去掉,加载完毕以后webview页面显示的非常可能是源代码!你没有看错,是源代码而不是界面。截个图就很直观了:

加载百度首页成了这样,当前的contentType包含这样的内容:text/html;charset=utf-8

去掉charset=utf-8,界面就变正常了:

通过抓包我们发现,我们添加的Header已经加上去了,即使打开二级页面也会添加:

细心的人可能会发现,怎么输入框右边的图标变成乱码了:

对比正常的界面:

这正是我遇到的还没解决的问题,通过PC端网页调试,虽然界面不大一样,这个图标大概应该是CSS文件当中一个background的png链接:

但为何通过okhttp3获取的输入流就没有加载成功,有知道问题根源或解决方案的麻烦告诉我下。目前对WebView并没有深入研究。测试了几个网站,也只有百度有这个问题。

 

 

 

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 9
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值