Add custom headers coming from android website

I need to add custom headers for EVERY request coming from a WebView . I know loadURL has a parameter for adding extra headers, but they only apply to some queries. All (resource related) requests do not contain headers. I looked through all the overrides in WebViewClient , but nothing allows adding headers to resource requests - onLoadResource(WebView view, String url) and shouldInterceptRequest(Webview,url) . Any help would be wonderful.

+4
source share
1 answer

shouldInterceptRequest(Webview,url) can help you intercept every site request, for example JavaScript, CSS, image. Then inside shouldInterceptRequest(Webview,url) you can use the url parameter for the initial new HTTP request using HttpClient and HttpPOST , here is an example code:

 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(); 

Then you can put responseInputStream in return WebResourceResponse(<content-type>, <encoding>, reponseInputStream) in shouldInterceptRequest(Webview,url)

if you have a query that doesn't need to add more headers, just filter it and return null , shouldInterceptRequest(Webview,url) will do the rest.

Hope this helps.

+8
source

Source: https://habr.com/ru/post/1498573/


All Articles