【问题标题】:Android WebView loadDataWithBaseURL shouldInterceptRequestAndroid WebView loadDataWithBaseURL shouldInterceptRequest
【发布时间】:2021-08-30 05:30:42
【问题描述】:

我正在使用 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 网址:data:text/html;charset=utf-8;base64,

shouldInterceptRequest2 网址:data:text/html;charset=utf-8;base64,

img 请求不会触发 shouldInterceptRequest。

怎么了?

【问题讨论】:

    标签: android request intercept webviewclient


    【解决方案1】:

    尽管文档是这样说的:

    为各种 URL 方案调用此回调(例如,http(s):, 数据:,文件:等),不仅是那些发送请求的方案 网络。这不适用于 javascript: URLs、blob: URLs 或 对于通过 file:///android_asset/ 或 file:///android_res/ 访问的资产 网址。

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

    【讨论】:

      猜你喜欢
      • 2017-10-08
      • 2013-09-13
      • 1970-01-01
      • 1970-01-01
      • 2013-05-09
      • 2016-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多