問題描述
android webview顯示windows-1250字符集html的問題 (Trouble with android webview displaying windows-1250 charset html)
I'd like to load a Windows-1250 encoded html page into a webview. Actually I wouldn't like, but I have to. An example of this encoding can be found here.
I can see the above page fine in any pc browser - android webview also displays the page properly.
What I need to do though, is to fetch a base64 encoded version of the above page, and load it into the webview from a String resource. So, as a test, I used this online tool to get the base64 encoded version of the page, added as a String to my application, and tried to load it via
myWebView.loadData(htmlResource, "text/html; charset=Windows-1250", "base64");
, where htmlResource contains the base64 encoded html source as a String. You can see the result below, character encoding is clearly messed up.
What's the proper way to display this page from a base64 encoded String?
EDIT: I also tried this approach, with the same results:
String decodedResource = new String(Base64.decode(htmlResource));
mWebView.loadDataWithBaseURL( null, decodedResource, "text/html",
"Windows-1250", null );
EDIT 2: I also tried snoblucha's suggestion with the following modification, still no luck:
try {
convertedResource = new String(Base64.decode(htmlResource), "windows-1250");
} catch (UnsupportedEncodingException e) {
Log.e("UnsupportedEncodingException", e.getMessage());
}
mWebView.loadData(convertedResource, "text/html", "windows-1250");
The encoding is still messed up, though slightly differently.
參考解法
方法 1:
Try to use this code:
String html = "Some string in windows-1250"; // Actually string in unicode
String encoded = Base64.encodeToString(html.getBytes("cp1250"), Base64.DEFAULT); // Convert to array of bytes in cp1250 and later to base64 string
webView.loadData(encoded, "text/html; charset=windows-1250", "base64"); // Load to WebView
See also this question.
方法 2:
I would choose second approach, at first decode Base64 then pass it to WebView. But you did not specify what encoding is the Base64 decoded array. Point it out in String constructor and it should work.
myWebView.loadData(new String(Base64.decode(htmlResource, Base64.DEFAULT),"windows-1250"), "text/html", "windows-1250");
方法 3:
What about performing following transformations on encoded string:
String decoded = new String(encoded.getBytes(), "Windows-1250");
(by András Szepesházi、Rudik Krasniynos、snoblucha、a.ch.)