Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding custom header to WebView by adding headers to WebResourceRequest's headers in shouldInterceptRequest doesn't work

I need to add a custom header to a page loading in WebView, but it doesn't work, header is not set:

@Override
public WebResourceResponse shouldInterceptRequest (WebView view,  WebResourceRequest request)
{
    request.getRequestHeaders().add("MyHeader","MyValue"); 
    return super.shouldInterceptRequest(view, request);
}

What I am doing wrong here? I'm running on Android 5.

I've seen many answers on SO saying that you have to do the HTTP request and return WebResourceResponse yourself. Is this because even if you modify headers like I do, they are ignored?

I also trying to find the location in the Android source code of the call to Where is the location of the call to the shouldInterceptRequest so I can see how it works myself, but I couldn't find it.

like image 796
Don Box Avatar asked Jan 06 '23 17:01

Don Box


2 Answers

I found the answer myself, it's right there in docs:

If the return value is null, the WebView will continue to load the resource as usual. Otherwise, the return response and data will be used.

Moreover, a simple test shows the base implementation of WebViewClient.shouldInterceptRequest returns null. So the WebView basically continues to load resource as usual.

In other words, I cannot just add a value to header and expect it to be used. I actually need to do the request myself and return the response.

Too bad there is no way to just modify header and have the default implementation use it.

I know I can set in headers by calling loadUrl method with headers, but the headers won't be used if I'm first loading a local page and then load online pages.

like image 84
Don Box Avatar answered Feb 18 '23 07:02

Don Box


Default method implementation of shouldInterceptRequest provided in the WebViewClient is returning null, hence if we need additional headers to be set then we have to create WebResourceResponse and return it.

https://android.googlesource.com/platform/frameworks/base.git/+/master/core/java/android/webkit/WebViewClient.java

like image 31
Clement Amarnath Avatar answered Feb 18 '23 06:02

Clement Amarnath