安卓。 WebView 和 loadData

发布于 2024-09-27 23:48:55 字数 266 浏览 3 评论 0 原文

可以使用以下方法进行网络视图的内容设置 loadData(String data, String mimeType, String encoding)

如何处理html数据编码未知的问题?!

有编码列表吗?

我从我的大学知道,在我的例子中,html 来自 DB 并使用 latin-1 编码。 我尝试将编码参数设置为 latin-1、ISO-8859-1 / iso-8859-1,但在显示 ä、ö、ü 等特殊符号时仍然存在问题。

我将非常感谢任何建议。

It's possible to use following method for content's setting of a web-view
loadData(String data, String mimeType, String encoding)

How to handle the problem with unknown encoding of html data?!

Is there a list of encodings?!

I know from my college that in my case html comes from DB and is encoded with latin-1.
I try to set encoding parameter to latin-1, to ISO-8859-1 / iso-8859-1, but still have problem with displaying of special signs like ä, ö, ü.

I'll be very thankful for any advice.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

緦唸λ蓇 2024-10-04 23:48:55
myWebView.loadData(myHtmlString, "text/html; charset=UTF-8", null);

这可以完美地工作,特别是在 Android 4.0 上,它显然忽略了 HTML 内部的字符编码。

在 2.3 和 4.0.3 上测试。

事实上,我不知道除了“base64”之外,最后一个参数还采用什么其他值。一些 Google 示例将 null 放在那里。

myWebView.loadData(myHtmlString, "text/html; charset=UTF-8", null);

This works flawlessly, especially on Android 4.0, which apparently ignores character encoding inside HTML.

Tested on 2.3 and 4.0.3.

In fact, I have no idea about what other values besides "base64" does the last parameter take. Some Google examples put null in there.

北音执念 2024-10-04 23:48:55

WebView.loadData() 根本无法正常工作。我必须做的是:

String header = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";
myWebView.loadData(header+myHtmlString, "text/html", "UTF-8");

我认为在你的情况下,你应该在标头和 WebView.loadData() 中将 UTF-8 替换为 latin1 或 ISO-8859-1 。

并且,为了给出完整的答案,这里是编码的官方列表: http://www.iana .org/assignments/character-sets

我更新我的答案以使其更具包容性:

使用WebView.loadData() 具有非 latin1 编码对 html 内容进行编码。前面的示例在 Android 4+ 中无法正常工作,因此我将其修改为如下所示:

WebSettings settings = myWebView.getSettings();
settings.setDefaultTextEncodingName("utf-8");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
    String base64 = Base64.encodeToString(htmlString.getBytes(), Base64.DEFAULT);
    myWebView.loadData(base64, "text/html; charset=utf-8", "base64");
} else {
    String header = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";
    myWebView.loadData(header + htmlString, "text/html; charset=UTF-8", null);

}

但后来我切换到 WebView.loadDataWithBaseURL( ) 并且代码变得非常干净,并且不依赖于 Android 版本:

WebSettings settings = myWebView.getSettings();
settings.setDefaultTextEncodingName("utf-8");
myWebView.loadDataWithBaseURL(null, htmlString, "text/html", "utf-8", null);

由于某种原因,这些函数具有完全不同的实现。

WebView.loadData() is not working properly at all. What I had to do was:

String header = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";
myWebView.loadData(header+myHtmlString, "text/html", "UTF-8");

I think in your case you should replace UTF-8 with latin1 or ISO-8859-1 both in header and in WebView.loadData().

And, to give a full answer, here is the official list of encodings: http://www.iana.org/assignments/character-sets

I update my answer to be more inclusive:

To use WebView.loadData() with non latin1 encodings you have to encode html content. Previous example was not correctly working in Android 4+, so I have modified it to look as follows:

WebSettings settings = myWebView.getSettings();
settings.setDefaultTextEncodingName("utf-8");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
    String base64 = Base64.encodeToString(htmlString.getBytes(), Base64.DEFAULT);
    myWebView.loadData(base64, "text/html; charset=utf-8", "base64");
} else {
    String header = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";
    myWebView.loadData(header + htmlString, "text/html; charset=UTF-8", null);

}

But later I have switched to WebView.loadDataWithBaseURL() and the code became very clean and not depending on Android version:

WebSettings settings = myWebView.getSettings();
settings.setDefaultTextEncodingName("utf-8");
myWebView.loadDataWithBaseURL(null, htmlString, "text/html", "utf-8", null);

For some reason these functions have completely different implementation.

可爱咩 2024-10-04 23:48:55

据我了解,loadData() 只是生成一个 data: URL,并提供数据。

阅读 javadocs

如果编码参数的值为'base64',则数据必须编码为base64。否则,数据必须对安全 URL 字符范围内的八位字节使用 ASCII 编码,并对该范围之外的八位字节使用 URL 的标准 %xx 十六进制编码。例如, '#', '%', '\', '?'应分别替换为 %23、%25、%27、%3f。

此方法形成的“数据”方案 URL 使用默认的 US-ASCII 字符集。如果您需要设置不同的字符集,则应形成一个“数据”方案 URL,该 URL 在 URL 的媒体类型部分中显式指定字符集参数,并改为调用 loadUrl(String)。请注意,从数据 URL 的媒体类型部分获取的字符集始终会覆盖 HTML 或 XML 文档本身中指定的字符集。

因此,您应该使用 US-ASCII 并自行转义任何特殊字符,或者仅使用 Base64 对所有内容进行编码。假设您使用 UTF-8,以下内容应该有效(我还没有使用 latin1 对此进行测试):

String data = ...;  // the html data
String base64 = android.util.Base64.encodeToString(data.getBytes("UTF-8"), android.util.Base64.DEFAULT);
webView.loadData(base64, "text/html; charset=utf-8", "base64");

As I understand it, loadData() simply generates a data: URL with the data provide it.

Read the javadocs for loadData():

If the value of the encoding parameter is 'base64', then the data must be encoded as base64. Otherwise, the data must use ASCII encoding for octets inside the range of safe URL characters and use the standard %xx hex encoding of URLs for octets outside that range. For example, '#', '%', '\', '?' should be replaced by %23, %25, %27, %3f respectively.

The 'data' scheme URL formed by this method uses the default US-ASCII charset. If you need need to set a different charset, you should form a 'data' scheme URL which explicitly specifies a charset parameter in the mediatype portion of the URL and call loadUrl(String) instead. Note that the charset obtained from the mediatype portion of a data URL always overrides that specified in the HTML or XML document itself.

Therefore, you should either use US-ASCII and escape any special characters yourself, or just encode everything using Base64. The following should work, assuming you use UTF-8 (I haven't tested this with latin1):

String data = ...;  // the html data
String base64 = android.util.Base64.encodeToString(data.getBytes("UTF-8"), android.util.Base64.DEFAULT);
webView.loadData(base64, "text/html; charset=utf-8", "base64");
白鸥掠海 2024-10-04 23:48:55

我有这个问题,但是:

String content = "<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" /></head><body>";
content += mydata + "</body></html>";
WebView1.loadData(content, "text/html", "UTF-8");

不适用于所有设备。我合并了一些方法:

String content = 
       "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"+
       "<html><head>"+
       "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />"+
       "</head><body>";

content += myContent + "</body></html>";

WebView WebView1 = (WebView) findViewById(R.id.webView1);
WebView1.loadData(content, "text/html; charset=utf-8", "UTF-8");

它有效。

I have this problem, but:

String content = "<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" /></head><body>";
content += mydata + "</body></html>";
WebView1.loadData(content, "text/html", "UTF-8");

not work in all devices. And I merge some methods:

String content = 
       "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"+
       "<html><head>"+
       "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />"+
       "</head><body>";

content += myContent + "</body></html>";

WebView WebView1 = (WebView) findViewById(R.id.webView1);
WebView1.loadData(content, "text/html; charset=utf-8", "UTF-8");

It works.

血之狂魔 2024-10-04 23:48:55

在Web视图中加载htmlContent的最安全方法是:

  1. 使用base64编码(官方推荐)
  2. 指定UFT-8作为html内容类型,即“text/html; charset=utf-8” “text/html”(个人建议)

“Base64 编码”是官方建议,已在Chrominium 最新 01/2019 错误中再次编写(已存在于 Javadoc 中) strong>(存在于 WebView M72 (72.0.3626.76) 中):

https: //bugs.chromium.org/p/chromium/issues/detail?id=929083

CHROMIUM 团队的官方声明:

“建议修复:
我们的团队建议您使用 Base64 对数据进行编码。我们提供了如何执行此操作的示例:

此修复是向后兼容的(它适用于早期的 WebView 版本),并且也应该是面向未来的(您不会遇到未来的兼容性问题)内容编码)。”

示例:

webView.loadData(
    Base64.encodeToString(
        htmlContent.getBytes(StandardCharsets.UTF_8),
        Base64.DEFAULT
    ), // encode in Base64 encoded 
    "text/html; charset=utf-8", // utf-8 html content (personal recommendation)
    "base64" // always use Base64 encoded data: NEVER PUT "utf-8" here (using base64 or not): This is wrong!
);  

The safest way to load htmlContent in a Web view is to:

  1. use base64 encoding (official recommendation)
  2. specify UFT-8 for html content type, i.e., "text/html; charset=utf-8" instead of "text/html" (personal advice)

"Base64 encoding" is an official recommendation that has been written again (already present in Javadoc) in the latest 01/2019 bug in Chrominium (present in WebView M72 (72.0.3626.76)):

https://bugs.chromium.org/p/chromium/issues/detail?id=929083

OFFICIAL statement from CHROMIUM TEAM:

"Recommended fix:
Our team recommends you encode data with Base64. We've provided examples for how to do so:

This fix is backwards compatible (it works on earlier WebView versions), and should also be future-proof (you won't hit future compatibility problems with respect to content encoding)."

Example:

webView.loadData(
    Base64.encodeToString(
        htmlContent.getBytes(StandardCharsets.UTF_8),
        Base64.DEFAULT
    ), // encode in Base64 encoded 
    "text/html; charset=utf-8", // utf-8 html content (personal recommendation)
    "base64" // always use Base64 encoded data: NEVER PUT "utf-8" here (using base64 or not): This is wrong!
);  
只是在用心讲痛 2024-10-04 23:48:55

使用这个:
字符串自定义Html =文本;

           wb.loadDataWithBaseURL(null,customHtml,"text/html", "UTF-8", null);

use this:
String customHtml =text ;

           wb.loadDataWithBaseURL(null,customHtml,"text/html", "UTF-8", null);
娇纵 2024-10-04 23:48:55
 String strWebData="html...." //**Your html string**

 WebView webDetail=(WebView) findViewById(R.id.webView1);

 WebSettings websetting = webDetail.getSettings();

 websetting.setDefaultTextEncodingName("utf-8");

 webDetail.loadData(strWebData, "text/html; charset=utf-8", null);
 String strWebData="html...." //**Your html string**

 WebView webDetail=(WebView) findViewById(R.id.webView1);

 WebSettings websetting = webDetail.getSettings();

 websetting.setDefaultTextEncodingName("utf-8");

 webDetail.loadData(strWebData, "text/html; charset=utf-8", null);
谁人与我共长歌 2024-10-04 23:48:55

上面的答案不适用于我的情况。需要在meta标签中指定utf-8

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    </head>
    <body>
        <!-- you content goes here -->
    </body>
</html>

the answers above doesn't work in my case. You need to specify utf-8 in meta tag

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    </head>
    <body>
        <!-- you content goes here -->
    </body>
</html>
浸婚纱 2024-10-04 23:48:55

这是快速且有效的 // data = 任何 html 或数学字符串

public void putInWebview(String data, WebView wv) {
        String htmlstring = "<head><meta name='viewport' content='width=device-width, shrink-to-fit=YES' user-scalable='no'><script type=\"text/x-mathjax-config\">MathJax.Hub.Config({tex2jax: {inlineMath: [['\\(','\\)']],processEscapes: true},\"HTML-CSS\": { linebreaks: { automatic: true, width: \"container\" } } } )</script><script id=\"MathJax-script\" async src=\"https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js\" ></script></head>" +
                "<body style=\"font-size:100%; font-family: Arial \"  > " + data + "</body></html>";
        String qstnencodedHtml = Base64.encodeToString(htmlstring.getBytes(), Base64.NO_PADDING);
        if (Build.VERSION.SDK_INT >= 19) {
            wv.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        }
        else {
            wv.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
        wv.getSettings().setJavaScriptEnabled(true);
        wv.loadData(qstnencodedHtml, "text/html", "base64");

    }

this is fast and working // data = any html or math string

public void putInWebview(String data, WebView wv) {
        String htmlstring = "<head><meta name='viewport' content='width=device-width, shrink-to-fit=YES' user-scalable='no'><script type=\"text/x-mathjax-config\">MathJax.Hub.Config({tex2jax: {inlineMath: [['\\(','\\)']],processEscapes: true},\"HTML-CSS\": { linebreaks: { automatic: true, width: \"container\" } } } )</script><script id=\"MathJax-script\" async src=\"https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js\" ></script></head>" +
                "<body style=\"font-size:100%; font-family: Arial \"  > " + data + "</body></html>";
        String qstnencodedHtml = Base64.encodeToString(htmlstring.getBytes(), Base64.NO_PADDING);
        if (Build.VERSION.SDK_INT >= 19) {
            wv.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        }
        else {
            wv.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
        wv.getSettings().setJavaScriptEnabled(true);
        wv.loadData(qstnencodedHtml, "text/html", "base64");

    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文