【问题标题】:Load data with base64 encoding with loadDataWithBaseURL使用 loadDataWithBaseURL 以 base64 编码加载数据
【发布时间】:2019-12-03 12:44:24
【问题描述】:

我有一个应用程序,它使用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 中发生了一些变化,而且确实发生了变化,doc 表示:

更严格的 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 字符串?

【问题讨论】:

  • 我也遇到了这个。你对这个问题了解更多了吗?

标签: android utf-8 base64 android-webview


【解决方案1】:

docs 说(强调添加)

如果base URL使用data scheme,这个方法相当于调用loadData(),historyUrl被忽略,数据会被当作data: URL的一部分,包括要求内容是URL-编码或base64编码。 如果基本 URL 使用任何其他方案,则数据将作为纯字符串(即不是数据 URL 的一部分)和字符串 中的任何 URL 编码实体加载到 WebView不会被解码

这听起来好像没有办法提供像https://example.com 这样的网站的基本 URL,不幸的是。

我能够通过使用html base tag 解决此问题,因此链接/图像/等中的相对 URL。仍然可以工作。

String header = "<head> <base href='" + myBaseUrl + "'> </head>";
String encodedHtml = Base64.encodeToString((header + resource).getBytes(), Base64.NO_WRAP);
webview.loadData(encodedHtml, "text/html; charset=utf-8", "base64");

【讨论】:

    【解决方案2】:

    我在没有标题的情况下解决了(Kotlin)。

    这是 base64 的错误或其他问题。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-31
      • 1970-01-01
      • 2020-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-21
      相关资源
      最近更新 更多