微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Android WebView loadDataWithBaseURL shouldInterceptRequest

如何解决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: data:text/html;charset=utf-8;base64,

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

img 请求不会触发 shouldInterceptRequest。

怎么了?

解决方法

尽管文档是这样说的:

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。