Mike Kwan
Mike Kwan

Reputation: 24447

How do I see request headers on Android WebView requests?

How can I intercept all requests made out of an Android WebView and get the corresponding request headers? I want to see the headers for every request made from my WebView including XHRs, script sources, css, etc.

The equivalent on iOS is to override NSURLCache which will give you all this information. The following are probably the closest to what I want but as far as I can see WebViewClient only ever gives us back strings:

void onLoadResource(WebView view, String url);
WebResourceResponse shouldInterceptRequest(WebView view, String url);

Upvotes: 20

Views: 27849

Answers (4)

Anton Prokopov
Anton Prokopov

Reputation: 641

I also had some problems with intercepting request headers in WebView myWebView.

First I tryed to do this with setting custom WebViewClient for myWebView.

myWebView.setWebViewClient(new WebViewClient() {

    @Override
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                Log.v("USERAGENTBROWSE", "shouldOverrideUrlLoading api >= 21 called");

                //some code

                return true;
            }

    @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.v("USERAGENTBROWSE", "shouldOverrideUrlLoading api < 21 called");

                //some code

                return true;
            }

});

But method shouldOverrideUrlLoading(...) was never called. And I have really no ideas why.

Then I found that there is the way to intercept some common headers like "User-Agent", "Cache-Control", etc.:

myWebView.getSettings().setUserAgentString("your_custom_user_agent_header");
myWebView.getSettings().setCacheMode(int mode);
...

Hope it may help somebody.

Upvotes: 4

Mayur More
Mayur More

Reputation: 981

webview.setWebViewClient(new WebViewClient() {
            @SuppressLint("NewApi")
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                Log.d("", "request.getRequestHeaders()::"+request.getRequestHeaders());

                return null;
            }
        });

Upvotes: 20

Fuong Lee
Fuong Lee

Reputation: 195

By this way you can enable debugging for web view application and using Chrome Developer Tools to see full details of your requests, responses, css, javascripts, etc

Upvotes: 0

sfinja
sfinja

Reputation: 756

You question sounds very similar to this one, so the immediate and unequivocal answer is that it is not possible to read the request headers on Android's WebView or WebViewClient.

There are workarounds, however, that could allow you get what you need. This answer describes in more detail how to do this.

Upvotes: 3

Related Questions