Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding custom header to all requests in shouldInterceptRequest Android webview

I want to add custom Headers to requests in the webview. I think it should be possible to do it in shouldInterceptRequest.. Since my minimum API level is less than 21 shouldInterceptRequest (final WebView view, final String url) is also called and therefore I need to add headers here as well but I am not sure how.

@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            request.getRequestHeaders().put("ClientId", "ANDROID");
            request.getRequestHeaders().put("Tokon", token);
        }

        return super.shouldInterceptRequest(view, request);
    }

    @Override
    public WebResourceResponse shouldInterceptRequest(final WebView view, final String url) {
        // I need to updated the header here

        return super.shouldInterceptRequest(view, url);
    }

There is a suggestion to use view.loadUrl(url,headers) but this does not work either.

like image 206
Ubaier Bhat Avatar asked Aug 16 '26 18:08

Ubaier Bhat


1 Answers

The difficulty you run into with pre API 21 is the shouldInterceptRequest only provides the intercepted URL and the webview without the body of the request. I ran into this same issue and discovered the following GitHub repository

https://github.com/KeejOow/android-post-webview

The important part of this project is interceptheader.html in the assets folder. This html contains javascript that is inserted at the top of every html response the webview loads. This JS intercepts every form and ajax submission from the page and loads the body data into a java class. Next the shouldInterceptRequest method determines whether the request is POST or GET (you only get those two, unfortunately) based on whether there is any data in the body.

Finally, once it has marshalled all the relevant information, it performs the request by itself (instead of passing it off to Android), returning the resulting WebResourceResponse.

Be warned that the repository has seen some aging. I had to do some fiddling to get pages to work as I wanted them.

The best place to add your headers is in the InterceptingWebViewClient class under shouldInterceptRequest.

conn.setRequestProperty("header-name", value);
like image 124
Jonathan Cameron Avatar answered Aug 19 '26 14:08

Jonathan Cameron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!