44

I need to modify the request header of the android webView request. So, I add the following code in the method shouldInterceptRequest.

Here is my code:

@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
    try {
        String mUrl = request.getUrl().toString();
        OkHttpClient httpClient = new OkHttpClient();
        Request mRequest = new Request.Builder()
                .url(request.getUrl().toString())
                .addHeader("token", UserHelper.getToken()) //add headers
                .build();
        Response response = httpClient.newCall(mRequest).execute();

        return new WebResourceResponse(
            getMimeType(request.getUrl().toString()), // set content-type
            response.header("content-encoding", "utf-8"),
            response.body().byteStream()
        );
    } catch (Exception e) {
        return super.shouldInterceptRequest(view, request);
    }
    return super.shouldInterceptRequest(view, request);
}

Actually, it works, all the requests carry the new header. However, because I construct the new request, the original request method/body was lost. I don't know how to keep the original method and body from the WebResourceRequest.

Yash Joshi
  • 557
  • 7
  • 25
郑凯拓
  • 441
  • 4
  • 3
  • Can you store the body in a instance variable and pass that a long in further requests? – reidisaki Oct 03 '19 at 19:01
  • 4
    Any solution yet? – DroidDev Aug 05 '20 at 16:31
  • 1
    @DroidDev I suspect Google's Android team built this limitation in by design (i.e. trying their best to block custom implementations of webviews) – AlanSTACK Sep 11 '22 at 23:33
  • 1
    Google seems to have added a private method to change this value in a [recent pull request.](https://issuetracker.google.com/issues/226552535) But management seems [hesitant on adding this feature in.](https://android-review.googlesource.com/c/platform/frameworks/support/+/2041643/) – AlanSTACK Sep 11 '22 at 23:47

1 Answers1

2

WebResourceRequest is an interface that can't read the request body, but you can use your own interface something like this repo dose.

https://github.com/KonstantinSchubert/request_data_webviewclient

webView.setWebViewClient(new WriteHandlingWebViewClient() {
   @Override
   public boolean shouldOverrideUrlLoading(WebView view, WriteHandlingWebResourceRequest request) {
        // works the same as WebViewClient.shouldOverrideUrlLoading, 
        // but you have request.getAjaxData() which gives you the 
        // request body
   }
});
Hamid Zandi
  • 2,714
  • 24
  • 32