Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add custom headers to WebView resource requests - android

I need to add custom headers to EVERY request coming from the WebView. I know loadURL has the parameter for extraHeaders, but those are only applied to the initial request. All subsequent 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). Any help would be wonderful.

Thanks, Ray

like image 620
Ray Avatar asked Sep 30 '11 13:09

Ray


2 Answers

Try

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

For adding headers to resources loading requests, make custom WebViewClient and override:

API 24+: WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) or WebResourceResponse shouldInterceptRequest(WebView view, String url) 
like image 56
peceps Avatar answered Oct 05 '22 02:10

peceps


You will need to intercept each request using WebViewClient.shouldInterceptRequest

With each interception, you will need to take the url, make this request yourself, and return the content stream:

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

If your minimum API target is level 21, you can use the new shouldInterceptRequest which gives you additional request information (such as headers) instead of just the URL.

like image 36
14 revs, 12 users 16% Avatar answered Oct 05 '22 00:10

14 revs, 12 users 16%