You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android WebView能否拦截并修改XHR/AJAX请求体?

Can Android WebView intercept and modify XHR request bodies?

Absolutely, you can pull this off—just keep in mind the Android API level compatibility (this works reliably on API 21+). Here's a practical, step-by-step breakdown of how to implement it:

Core Approach

The trick is overriding shouldInterceptRequest() in your WebViewClient to catch the target XHR request, extract and tweak its body, re-send the request manually, and pass the modified response back to the WebView.

Step-by-Step Implementation

1. Override the right shouldInterceptRequest method

For Android 5.0 (API 21) and above, use the overload that accepts WebResourceRequest—this gives you access to critical details like the request body, HTTP method, and full URL:

webView.setWebViewClient(new WebViewClient() {
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
        // Target only your specific URL and POST requests (XHR bodies are usually sent via POST)
        if (request.getUrl().toString().equals("YOUR_TARGET_URL") && request.getMethod().equalsIgnoreCase("POST")) {
            try {
                // Step 2: Extract the original request body
                WebResourceRequestBody originalRequestBody = request.getRequestBody();
                InputStream bodyStream = originalRequestBody.getInputStream();
                // Convert stream to byte array (use Apache Commons IO or implement manual reading)
                byte[] originalBodyBytes = IOUtils.toByteArray(bodyStream);
                String originalBody = new String(originalBodyBytes, StandardCharsets.UTF_8);

                // Step 3: Parse and modify the body
                // Example for JSON-formatted bodies
                JSONObject jsonBody = new JSONObject(originalBody);
                jsonBody.put("your_target_key", "new_modified_value"); // Update the desired field
                String modifiedBody = jsonBody.toString();
                byte[] modifiedBodyBytes = modifiedBody.getBytes(StandardCharsets.UTF_8);

                // Step 4: Re-send the request with the modified body
                OkHttpClient client = new OkHttpClient();
                Request newRequest = new Request.Builder()
                        .url(request.getUrl().toString())
                        .headers(Headers.of(request.getRequestHeaders()))
                        .post(RequestBody.create(modifiedBodyBytes, MediaType.parse(originalRequestBody.getContentType())))
                        .build();

                Response response = client.newCall(newRequest).execute();

                // Step 5: Wrap the response for WebView to process
                return new WebResourceResponse(
                        response.header("Content-Type", "text/plain"),
                        response.header("Content-Encoding", "utf-8"),
                        response.body().byteStream()
                );
            } catch (Exception e) {
                e.printStackTrace();
                // Fallback: Let WebView handle the request normally if something breaks
                return super.shouldInterceptRequest(view, request);
            }
        }
        // Pass all other requests through as normal
        return super.shouldInterceptRequest(view, request);
    }
});

2. Key Notes & Caveats

  • API Level Limit: Before API 21, the older shouldInterceptRequest(WebView, String) overload doesn't expose the request body—so modifying it isn't possible on those versions.
  • Body Parsing: Adjust the parsing logic to match your actual request body format (e.g., form-data, XML, or plain text). For form-data, split the string by & to edit key-value pairs.
  • Threading: shouldInterceptRequest() runs on a background thread, so you don't need to wrap network calls in an AsyncTask or coroutine here.
  • Error Handling: Always include fallback logic to return the default request handling if any step fails (like parsing errors or network issues) to avoid breaking the WebView's functionality.
  • Permissions: Don't forget to add <uses-permission android:name="android.permission.INTERNET" /> to your manifest for network access.

Summary

If your app targets API 21 or higher, this approach works seamlessly for intercepting XHR requests, modifying their bodies, and re-sending them. For older API levels, this isn't feasible with standard WebView APIs.

内容的提问来源于stack exchange,提问作者Redeye

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:43:47