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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With