现在的位置: 首页 > 综合 > 正文

utf-8编码问题之urlencode和getbytes得到的utf-8区别验证测试

2013年12月03日 ⁄ 综合 ⁄ 共 1028字 ⁄ 字号 评论关闭

 上个星期又发生了一起编码问题引起的bug,继续研究。其中涉及URLEncode对字符串进行utf-8编码和getbytes对字符串进行utf-8编码的区别。

详细研究结论如下

首先utf-8编码的中文是采用三个字节一个中文来存储的。

验证代码如下

String msg = "中国";

System.out.println(msg.getBytes("utf-8").length);

打印出:6

采用URLEncode来打印msg

System.out.println(URLEncoder.encode(msg,"utf-8"));

打印出:

%E4%B8%AD%E5%9B%BD

我们希望通过验证getbytes得到utf-8和URLEncodeer得到utf-8是一致的代码如下

  String xyz="中";
  String xyg="国";

  System.out.println(Integer.toHexString(0xff & xyz.getBytes("utf-8")[0]));
  System.out.println(Integer.toHexString(0xff & xyz.getBytes("utf-8")[1]));
  System.out.println(Integer.toHexString(0xff & xyz.getBytes("utf-8")[2]));
  System.out.println(Integer.toHexString(0xff & xyg.getBytes("utf-8")[0]));
  System.out.println(Integer.toHexString(0xff & xyg.getBytes("utf-8")[1]));
  System.out.println(Integer.toHexString(0xff & xyg.getBytes("utf-8")[2]));

打印出:

e4
b8
ad
e5
9b
bd

是否证明两者是相同的,答案是否定的

因为URLEncode还会做一些特殊处理,对一些特殊字符串

String xys = " ";

System.out.println(URLEncoder.encode(xys ,"utf-8"));

打印出:"+"

System.out.println(Integer.toHexString(0xff & xys.getBytes("utf-8")[0]));

打印出:"20"

对于普通英文,两者也是一致的。

 

抱歉!评论已关闭.