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

2022-08-31 08:55:33

我需要将自定义标头添加到来自 WebView 的每个请求中。我知道有 参数 为 ,但这些参数只适用于初始请求。所有后续请求都不包含标头。我已经查看了 中的所有覆盖,但没有任何内容允许将标头添加到资源请求 - 。任何帮助都会很棒。loadURLextraHeadersWebViewClientonLoadResource(WebView view, String url)

谢谢,雷


答案 1

尝试

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

要将标头添加到资源加载请求,请创建自定义 WebViewClient 并覆盖:

API 24+:
WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request)
or
WebResourceResponse shouldInterceptRequest(WebView view, String url)

答案 2

您需要使用 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。


推荐