为了账号安全,请及时绑定邮箱和手机立即绑定

将自定义标头添加到WebView资源请求-Android

将自定义标头添加到WebView资源请求-Android

交互式爱情 2019-11-11 16:00:20
我需要向来自WebView的每个请求添加自定义标头。我知道loadURL具有的参数extraHeaders,但这些参数仅应用于初始请求。所有后续请求均不包含标头。我已经看过所有重写WebViewClient,但是没有任何内容允许将标头添加到资源请求- onLoadResource(WebView view, String url)。任何帮助都会很棒。谢谢,雷
查看完整描述

3 回答

?
慕虎7371278

TA贡献1802条经验 获得超4个赞

尝试


loadUrl(String url, Map<String, String> extraHeaders)

要将标头添加到资源加载请求中,请自定义WebViewClient并重写:


API 24+:

WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request)

or

WebResourceResponse shouldInterceptRequest(WebView view, String url)


查看完整回答
反对 回复 2019-11-11
?
阿波罗的战车

TA贡献1862条经验 获得超6个赞

您将需要使用WebViewClient.shouldInterceptRequest拦截每个请求


每次拦截时,您都需要获取url,自行提出此请求,然后返回内容流:


WebViewClient wvc = new WebViewClient() {

    @Override

    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {


        try {

            DefaultHttpClient client = new DefaultHttpClient();

            HttpGet httpGet = new HttpGet(url);

            httpGet.setHeader("MY-CUSTOM-HEADER", "header value");

            httpGet.setHeader(HttpHeaders.USER_AGENT, "custom user-agent");

            HttpResponse httpReponse = client.execute(httpGet);


            Header contentType = httpReponse.getEntity().getContentType();

            Header encoding = httpReponse.getEntity().getContentEncoding();

            InputStream responseInputStream = httpReponse.getEntity().getContent();


            String contentTypeValue = null;

            String encodingValue = null;

            if (contentType != null) {

                contentTypeValue = contentType.getValue();

            }

            if (encoding != null) {

                encodingValue = encoding.getValue();

            }

            return new WebResourceResponse(contentTypeValue, encodingValue, responseInputStream);

        } catch (ClientProtocolException e) {

            //return null to tell WebView we failed to fetch it WebView should try again.

            return null;

        } catch (IOException e) {

             //return null to tell WebView we failed to fetch it WebView should try again.

            return null;

        }

    }

}


Webview wv = new WebView(this);

wv.setWebViewClient(wvc);

如果您的最低API目标是21级,则可以使用新的shouldInterceptRequest,它为您提供其他请求信息(例如标头),而不仅仅是URL。


查看完整回答
反对 回复 2019-11-11
  • 3 回答
  • 0 关注
  • 895 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信