How do I see request headers on Android WebView re

2020-08-13 06:41发布

问题:

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);

回答1:

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

                return null;
            }
        });


回答2:

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.



回答3:

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.



回答4:

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