在WebView中拦截POST请求

Fab*_*_34 30 post android request webview

我正在开发一个Android应用程序,用于过滤请求(使用白名单)并使用自定义SSLSocketFactory.为此,我开发了一个自定义WebViewClient,我已经覆盖了该shouldInterceptRequest方法.我可以过滤和使用我SocketFactory的GET请求,但我不能拦截POST请求.

那么,有没有办法拦截POST请求WebView

这是shouldInterceptRequest方法的代码:

public final WebResourceResponse shouldInterceptRequest(WebView view, String urlStr) {
    URI uri = URI.create(urlStr);
    String scheme = uri.getScheme();
    // If scheme not http(s), let the default webview manage it
    if(!"http".equals(scheme) && !"https".equals(scheme)) {
        return null;
    }
    URL url = uri.toURL();

    if(doCancelRequest(url)) {
        // Empty response
        Log.d(TAG, "URL filtered: " + url);
        return new WebResourceResponse("text/plain", "UTF-8", new EmptyInputStream());

    } else {
        Log.d(TAG, "URL: " + url);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("User-Agent", mSettings.getUserAgentString());

        // Configure connections
        configureConnection(conn);

        String mimeType = conn.getContentType();
        String encoding = conn.getContentEncoding();

        if(mimeType != null && mimeType.contains(CONTENT_TYPE_SPLIT)) {
            String[] split = mimeType.split(CONTENT_TYPE_SPLIT);
            mimeType = split[0];

            Matcher matcher = CONTENT_TYPE_PATTERN.matcher(split[1]);
            if(matcher.find()) {
                encoding = matcher.group(1);
            }
        }

        InputStream is = conn.getInputStream();
        return new WebResourceResponse(mimeType, encoding, is);
    }
}
Run Code Online (Sandbox Code Playgroud)

Kon*_*ert 5

几天前我也面临着同样的问题。

所以我建立了一个库来解决它:

https://github.com/KonstantinSchubert/request_data_webviewclient

它是带有自定义WebResourceRequest的WebViewClient,其中包含XMLHttpRequest请求的POST / PUT / ...有效负载。

但是,它仅适用于这些应用程序-不适用于表单和其他类型的请求源。

基本上,通过将脚本注入到HTML中以拦截XMLHttpRequest调用,此黑客才能正常工作。它记录了post / put / ...的内容,并将其发送到android.webkit.JavascriptInterface。在那里,请求一直保存到该shouldInterceptRequest方法被Android调用为止。

  • 这个问题非常聪明的黑客。谢谢。转换为使用 Xamarin.Android 并在遇到此问题时挽救了这一天。 (2认同)
  • 好主意,我冒昧地创建了您的库的更新和扩展版本:https://github.com/acsbendi/Android-Request-Inspector-WebView。我添加了对缺失部分的支持,例如表单和获取请求,以及记录确切的标头。 (2认同)

Raa*_*nan -4

使用 GET 而不是 POST。

已知问题: http://code.google.com/p/android/issues/detail? id=9122

也在这里得到了回答: Android - how toIntercept a form POST in android WebViewClient on API level 4

  • 是的,我在 android bugtracker 中发现了这个问题。但就我而言,我无法将 POST 更改为 GET 请求,因为我不知道我将连接到哪个服务器。例如,我无法连接到 GMail,因为身份验证期间存在 POST 请求。 (8认同)