<p>上个星期又发生了一起编码问题引起的bug,继续研究。其中涉及URLEncode对字符串进行utf-8编码和getbytes对字符串进行utf-8编码的区别。</p>
<p>详细研究结论如下</p>
<p>首先utf-8编码的中文是采用三个字节一个中文来存储的。</p>
<p>验证代码如下</p>
<p>String msg = "中国";</p>
<p>System.out.println(msg.getBytes("utf-8").length);</p>
<p>打印出:6</p>
<p>采用URLEncode来打印msg</p>
<p>System.out.println(URLEncoder.encode(msg,"utf-8"));</p>
<p>打印出:</p>
<p>%E4%B8%AD%E5%9B%BD</p>
<p>我们希望通过验证getbytes得到utf-8和URLEncodeer得到utf-8是一致的代码如下</p>
<p>String xyz="中";<br>String xyg="国";</p>
<p>System.out.println(Integer.toHexString(0xff & xyz.getBytes("utf-8")[0]));<br>System.out.println(Integer.toHexString(0xff & xyz.getBytes("utf-8")[1]));<br>System.out.println(Integer.toHexString(0xff & xyz.getBytes("utf-8")[2]));<br>System.out.println(Integer.toHexString(0xff & xyg.getBytes("utf-8")[0]));<br>System.out.println(Integer.toHexString(0xff & xyg.getBytes("utf-8")[1]));<br>System.out.println(Integer.toHexString(0xff & xyg.getBytes("utf-8")[2]));</p>
<p>打印出:</p>
<p>e4<br>b8<br>ad<br>e5<br>9b<br>bd</p>
<p>是否证明两者是相同的,答案是否定的</p>
<p>因为URLEncode还会做一些特殊处理,对一些特殊字符串</p>
<p>String xys = " ";</p>
<p>System.out.println(URLEncoder.encode(xys ,"utf-8"));</p>
<p>打印出:"+"</p>
<p>System.out.println(Integer.toHexString(0xff & xys.getBytes("utf-8")[0]));</p>
<p>打印出:"20"</p>
<p>对于普通英文,两者也是一致的。</p>
<p></p>
<p>详细研究结论如下</p>
<p>首先utf-8编码的中文是采用三个字节一个中文来存储的。</p>
<p>验证代码如下</p>
<p>String msg = "中国";</p>
<p>System.out.println(msg.getBytes("utf-8").length);</p>
<p>打印出:6</p>
<p>采用URLEncode来打印msg</p>
<p>System.out.println(URLEncoder.encode(msg,"utf-8"));</p>
<p>打印出:</p>
<p>%E4%B8%AD%E5%9B%BD</p>
<p>我们希望通过验证getbytes得到utf-8和URLEncodeer得到utf-8是一致的代码如下</p>
<p>String xyz="中";<br>String xyg="国";</p>
<p>System.out.println(Integer.toHexString(0xff & xyz.getBytes("utf-8")[0]));<br>System.out.println(Integer.toHexString(0xff & xyz.getBytes("utf-8")[1]));<br>System.out.println(Integer.toHexString(0xff & xyz.getBytes("utf-8")[2]));<br>System.out.println(Integer.toHexString(0xff & xyg.getBytes("utf-8")[0]));<br>System.out.println(Integer.toHexString(0xff & xyg.getBytes("utf-8")[1]));<br>System.out.println(Integer.toHexString(0xff & xyg.getBytes("utf-8")[2]));</p>
<p>打印出:</p>
<p>e4<br>b8<br>ad<br>e5<br>9b<br>bd</p>
<p>是否证明两者是相同的,答案是否定的</p>
<p>因为URLEncode还会做一些特殊处理,对一些特殊字符串</p>
<p>String xys = " ";</p>
<p>System.out.println(URLEncoder.encode(xys ,"utf-8"));</p>
<p>打印出:"+"</p>
<p>System.out.println(Integer.toHexString(0xff & xys.getBytes("utf-8")[0]));</p>
<p>打印出:"20"</p>
<p>对于普通英文,两者也是一致的。</p>
<p></p>