我正在调试一个第三方网关系统,它将二进制消息转换为 XML Web 服务。当它接收到包含特殊字符 0x80、0x81、0x82 和 0x83 的消息时会出现问题,它们没有正确地作为 XML 发送。
我已将问题范围缩小到他们将 byte[] 转换为 String 的位置,并制作了一个简单的示例来说明问题所在。特殊值都被翻译成相同的“未知”字符。
public static void main(String[] args) {
test(0x80);test(0x81);test(0x82);test(0x83);
}
public static void test(int value) {
String message = new String(new byte[]{(byte)value});
System.out.println(value + " => " + message + " => " + Arrays.toString(message.getBytes()));
}
输出
128 => � => [-17, -65, -67]
129 => � => [-17, -65, -67]
130 => � => [-17, -65, -67]
131 => � => [-17, -65, -67]
我想知道这应该如何解决。我尝试更改他们的代码以使用显式字符集
new String(bytes, Charset.forName("UTF-8"))
然而,这会导致同样的问题。值 0x80-0x83 似乎不作为有效的 XML 实体存在。
我发现你可以使用哪种工作的字符构造函数,但翻译以下内容,我不确定这是否正确?
new String(new char[]{(char) value}, 0, 1);
输出
128 => weird box character 0080 => [-62, -128]
129 => weird box character 0081 => [-62, -127]
130 => weird box character 0082 => [-62, -126]
131 => weird box character 0083 => [-62, -125]