Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add custom headers coming from android webview [duplicate]

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

like image 679
Gopichand Avatar asked Aug 23 '13 10:08

Gopichand


1 Answers

shouldInterceptRequest(Webview,url) can help you to intercept every request of a site, such as JavaScript, CSS, Image. Then inside shouldInterceptRequest(Webview,url) you can use the parameter url to initial new http request by using HttpClient and HttpPOST, here is 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 to return WebResourceResponse(<content-type>, <encoding>, reponseInputStream) in your shouldInterceptRequest(Webview,url)

if you have any request which doesn't need add more header, just filter it and return null, shouldInterceptRequest(Webview,url) will do the rest.

Hope this can help.

like image 75
admar.kevin Avatar answered Oct 20 '22 07:10

admar.kevin