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

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


谢谢,雷


交互式爱情
浏览 905回答 3
3回答

慕虎7371278

尝试loadUrl(String url, Map<String, String> extraHeaders)要将标头添加到资源加载请求中,请自定义WebViewClient并重写:API 24+:WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request)orWebResourceResponse shouldInterceptRequest(WebView view, String url)

阿波罗的战车

您将需要使用WebViewClient.shouldInterceptRequest拦截每个请求每次拦截时,您都需要获取url,自行提出此请求,然后返回内容流:WebViewClient wvc = new WebViewClient() {&nbsp; &nbsp; @Override&nbsp; &nbsp; public WebResourceResponse shouldInterceptRequest(WebView view, String url) {&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; DefaultHttpClient client = new DefaultHttpClient();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; HttpGet httpGet = new HttpGet(url);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; httpGet.setHeader("MY-CUSTOM-HEADER", "header value");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; httpGet.setHeader(HttpHeaders.USER_AGENT, "custom user-agent");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; HttpResponse httpReponse = client.execute(httpGet);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Header contentType = httpReponse.getEntity().getContentType();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Header encoding = httpReponse.getEntity().getContentEncoding();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; InputStream responseInputStream = httpReponse.getEntity().getContent();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String contentTypeValue = null;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String encodingValue = null;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (contentType != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; contentTypeValue = contentType.getValue();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (encoding != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; encodingValue = encoding.getValue();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return new WebResourceResponse(contentTypeValue, encodingValue, responseInputStream);&nbsp; &nbsp; &nbsp; &nbsp; } catch (ClientProtocolException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //return null to tell WebView we failed to fetch it WebView should try again.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; &nbsp; &nbsp; } catch (IOException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//return null to tell WebView we failed to fetch it WebView should try again.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}Webview wv = new WebView(this);wv.setWebViewClient(wvc);如果您的最低API目标是21级,则可以使用新的shouldInterceptRequest,它为您提供其他请求信息(例如标头),而不仅仅是URL。
打开App,查看更多内容
随时随地看视频慕课网APP