Don Box
Don Box

Reputation: 3336

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.

Upvotes: 5

Views: 5584

Answers (3)

Dunfield
Dunfield

Reputation: 785

I was able to add a custom header to the response using this code in one of my shouldInterceptRequest handlers:

InputStream is = new ByteArrayInputStream(result.getBytes());
WebResourceResponse resp = new WebResourceResponse("text/html", null, is);
Map<String, String> hdrs = resp.getResponseHeaders();
Map<String, String> newHdrs = new HashMap<>();
if(hdrs != null) newHdrs.putAll(hdrs);
newHdrs.put("Access-Control-Allow-Origin", "*");
resp.setResponseHeaders(newHdrs);
return resp;

Note that this is 5 years after the original post and I'm coding to API 30

Upvotes: 0

Clement Amarnath
Clement Amarnath

Reputation: 5466

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

Upvotes: 2

Don Box
Don Box

Reputation: 3336

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.

Upvotes: 7

Related Questions