HTML特殊字符解码

5

在Android上使用Java,我正在努力转换一些HTML特殊字符。

到目前为止,我尝试了以下方法:

String myString = "%A32.00%20per%20month%B3";

Html.fromHtml(myString).toString(); => %A32.00%20per%20month%B3
URLDecoder.decode(myString) => �2.00 per month�
URLDecoder.decode(myString, "UTF-8") => �2.00 per month�
URLDecoder.decode(myString, "ASCII") => �2.00 per month�
org.apache.commons.lang.StringEscapeUtils.unescapeHtml4(myString) => %A32.00%20per%20month%B3

正确的输出应该是 => 每月 £2.00³

1
你确定 URLDecoder.decode(myString, "UTF-8") 没有正确解码,而你的输出只是无法显示 £³ 字符吗? - Thomas
Apache Commons StringEscapeUtils可以转义/反转义HTML,但这不是你需要的。例如:£2.00每月³ <-> £2.00每月³ - proko
2个回答

8

你的字符串采用 ISO-8859-1 编码,因此 ASCII 和 UTF-8 不适用。

String myString = "%A32.00%20per%20month%B3";
URLDecoder.decode(myString, "ISO-8859-1");
// output: £2.00 per month³

2
public static void main(String[] args) throws UnsupportedEncodingException {
    String before = "£2.00 per month³";
    String encoded = URLEncoder.encode(before, "UTF-8");
    String decoded = URLDecoder.decode(encoded, "UTF-8");
    System.out.println(encoded);
    System.out.println(decoded);
}

我得到的输出是:
%C2%A32.00+per+month%C2%B3
£2.00 per month³

您确定 %A32.00%20每月%B3 是正确的吗?


完全正确,问题出在输入字符串(来自第三方网络服务)似乎对字符串进行了错误编码。当您在符号前面添加%C2时,它可以正常工作。谢谢。 - scottyab

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接