Android WebView 监听所有请求结果:方法详解及 Stetho 工具推荐
您可以使用 WebViewClient 的 shouldInterceptRequest 方法来拦截所有请求并获取请求结果。在这个方法中,您可以使用 HttpURLConnection 或 OkHttp 等网络库来发送请求并获取结果。以下是一个简单的示例:
webView.setWebViewClient(new WebViewClient() {
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
try {
URL url = new URL(request.getUrl().toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(request.getMethod());
// 设置请求头
for (Map.Entry<String, String> entry : request.getRequestHeaders().entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
conn.connect();
// 获取响应码
int responseCode = conn.getResponseCode();
// 获取响应头
Map<String, String> headers = new HashMap<>();
for (Map.Entry<String, List<String>> entry : conn.getHeaderFields().entrySet()) {
String key = entry.getKey();
String value = entry.getValue().get(0);
headers.put(key, value);
}
// 获取响应体
InputStream inputStream = conn.getInputStream();
// 构造 WebResourceResponse 对象
return new WebResourceResponse(conn.getContentType(), conn.getContentEncoding(), responseCode, headers, inputStream);
} catch (IOException e) {
e.printStackTrace();
}
return super.shouldInterceptRequest(view, request);
}
});
您也可以使用 Stetho 库来方便地查看 WebView 的网络请求。Stetho 是 Facebook 开源的一个 Android 调试工具,它可以在 Chrome 开发者工具中显示应用程序的网络请求、数据库、SharedPreferences 等信息。您可以在此处找到 Stetho 的 GitHub 地址:https://github.com/facebook/stetho。
原文地址: https://www.cveoy.top/t/topic/odsF 著作权归作者所有。请勿转载和采集!