添加来自android webview的自定义标头

Gop*_*and 4 android webview

我需要为来自的每个请求添加自定义标头WebView.我知道loadURL有添加额外标题的参数,但这些只适用于部分请求.所有(资源相关的)请求都不包含标头.我已经查看了所有覆盖内容WebViewClient,但没有任何内容允许向资源请求添加标头 - onLoadResource(WebView view, String url)shouldInterceptRequest(Webview,url).任何帮助都会很精彩.

adm*_*vin 8

shouldInterceptRequest(Webview,url)可以帮助您拦截网站的每个请求,例如JavaScript,CSS,Image.然后里面shouldInterceptRequest(Webview,url)你可以使用参数url使用初始新的HTTP请求HttpClientHttpPOST,这里是示例代码:

DefaultHttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(<"your url for each request">);
httpPost.setHeader("<header-name>", "<header-value>");
HttpReponse httpResponse = client.execute(httpPost);

//here omit getting content-type and encoding

InputStream reponseInputStream = httpReponse.getEntity().getContent();
Run Code Online (Sandbox Code Playgroud)

然后,你可以把responseInputStreamreturn WebResourceResponse(<content-type>, <encoding>, reponseInputStream)你的shouldInterceptRequest(Webview,url)

如果你有任何不需要添加更多标题的请求,只需过滤它return null,shouldInterceptRequest(Webview,url)然后完成剩下的工作.

希望这可以提供帮助.