在 WebView 中拦截 POST 请求 [英] Intercept POST requests in a WebView
问题描述
我正在开发一个 Android 应用程序来过滤请求(带有白名单)并使用自定义 SSLSocketFactory
.为此,我开发了一个自定义 WebViewClient
并覆盖了 shouldInterceptRequest
方法.我可以过滤和使用我的 SocketFactory
和 GET 请求,但我无法拦截 POST 请求.
I'm developping an Android application filtering the requests (with a white list) and using a custom SSLSocketFactory
. For this, I've developed a custom WebViewClient
and I have overridden the shouldInterceptRequest
method. I can filter and use my SocketFactory
with the GET requests but I can't intercept the POST requests.
那么,有没有办法拦截 WebView
中的 POST 请求?
So, is there a way to intercept the POST requests in a WebView
?
这里是 shouldInterceptRequest 方法的代码:
Here is the code of the shouldInterceptRequest method :
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);
}
}
推荐答案
几天前我遇到了同样的问题.
I was facing the same issue a few days ago.
所以我建立了一个解决它的库:
So I built a library that solves it:
https://github.com/KonstantinSchubert/request_data_webviewclient
它是一个带有自定义 WebResourceRequest 的 WebViewClient,其中包含 XMLHttpRequest 请求的 POST/PUT/... 负载.
It is a WebViewClient with a custom WebResourceRequest that contains the POST/PUT/... payload of XMLHttpRequest requests.
它只适用于这些 - 不适用于表单和其他类型的请求源.
It only works for these though - not for forms and other kind of request sources.
hack 的工作原理基本上是通过将脚本注入到拦截 XMLHttpRequest 调用的 HTML 中.它记录 post/put/... 内容并将其发送到 android.webkit.JavascriptInterface
.在那里,请求被隐藏,直到 shouldInterceptRequest
方法被 Android 调用......
The hack works, basically, by injecting a script into the HTML that intercepts XMLHttpRequest calls. It records the post/put/... content and sends it to an android.webkit.JavascriptInterface
. There, the request is stashed until the shouldInterceptRequest
method is called by Android ...
这篇关于在 WebView 中拦截 POST 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!