首页 > 解决方案 > Android WebView loadDataWithBaseURL shouldInterceptRequest

问题描述

我正在使用 WebView 显示带有 img 标签的 HTML 字符串。这些标签必须显示存储在 ZIP 存档中的图片,因此我需要拦截图片请求以返回 ZipInputStream。

因此,我使用 loadDataWithBaseURL 和 shouldInterceptRequest,但我的图片请求从未调用过 shouldInterceptRequest。这是我的 WebViewClient 客户端:

webView.webViewClient = object : WebViewClient() {

    override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest?): WebResourceResponse? {
        println("shouldInterceptRequest1 url: ${request?.url}")
        return super.shouldInterceptRequest(view, request)
    }

    override fun shouldInterceptRequest(view: WebView?, url: String?): WebResourceResponse? {

        println("shouldInterceptRequest2 url: $url")

        @Suppress("DEPRECATION")
        return super.shouldInterceptRequest(view, url)
    }
}

这是我加载 HTML 的方法:

webView.loadDataWithBaseURL(null, "<div><img src='file://path/to/my/image.png'/></div>", "text/html", "UTF-8", null)

我在 logcat 中得到的只是:

shouldInterceptRequest1 url: 数据:text/html;charset=utf-8;base64,

shouldInterceptRequest2 url: 数据:text/html;charset=utf-8;base64,

img 请求不会触发 shouldInterceptRequest。

怎么了?

标签: androidrequestinterceptwebviewclient

解决方案


尽管医生这样说:

该回调被各种 URL 方案调用(例如,http(s):、data:、file: 等),而不仅仅是那些通过网络发送请求的方案。这不适用于 javascript: URL、blob: URL 或通过 file:///android_asset/ 或 file:///android_res/ URL 访问的资产。

在我非常基本的示例代码中,在使用 loadDataWithBaseURL 时不为 file:// URI 调用 shouldInterceptRequest ... 使用 http:// 方案有效。


推荐阅读