首页 > 解决方案 > 使用 loadDataWithBaseURL 以 base64 编码加载数据

问题描述

我有一个应用程序用于WebView向用户显示一些本地 html。该应用程序在过去 2 年运行良好,但最近我收到太多关于该应用程序显示如下错误的报告:

"Web page not available The web page at data:text/html; charset=utf-8;charset=utf-8;base64, could not be loaded because: net::ERR_INVALID_RESPONSE"

显然,在 android 或 WebView 中发生了一些变化,并且确实发生了变化,文档说:

更严格的 UTF-8 解码器 在 Android 9 中,Java 语言的 UTF-8 解码器更加严格,并且遵循 Unicode 标准。

所以,我尝试用base64编码加载我的数据来解决这个问题。

String encodedHtml = Base64.encodeToString(resource.getBytes(), Base64.NO_WRAP);
loadDataWithBaseURL(basePath, encodedHtml, "text/html; charset=utf-8", "base64", null);

但是这个方法只打印原始的 base64 字符串。所以我尝试了这个:

loadData(encodedHtml, "text/html; charset=utf-8", "base64");

它显示html没有任何问题。

但是,我需要使用loadDataWithBaseURL,所以我可以发布处理 html,例如。加载css、字体等。

那么两者之间有什么区别loadDataloadDataWithBaseURL导致其中一个显示 html 而另一个显示原始 base64 字符串?

标签: androidutf-8base64android-webview

解决方案


我解决了没有标题(Kotlin)。

这是base64的错误或其他东西。

webview
            .loadDataWithBaseURL(
                "http://baseurl.com/",
                data?.fromBase64(),
                "text/html; charset=utf-8",
                "UTF-8",
                null
            )

fromBase64() -> https://stackoverflow.com/a/64892843/1064316


推荐阅读