JAVA–编码和解码
在web浏览器中,不同的浏览器的编码和解码的规则是不一样的
-
对于W3C浏览器:遵循W3C组织规范的浏览器(非IE浏览器)
//W3C编码 byte[] data = "哈哈haha 123".getBytes("UTF-8"); for (byte b : data) { System.out.print(b);//-27-109-120-27-109-120104971049732495051 } //W3C解码 String string = new String(data, "UTF-8"); System.out.println("\n"+string);//哈哈haha 123
-
对于IE浏览器,使用MIME机制
MIME机制对String编码时的规则:
- 字母数字字符保持不变
- 特殊字符“ . ”“ _ ”“ * ”和“-”保持不变
- 空格“ ”转换为“+”
MIME编码用URLEncoder.encode(String str,“编码格式”)方法,
MIME解码用URLDecoder.decode(String str,“解码格式”)方法
相关代码
public class EncodingDemo {
public static void main(String[] args) throws Exception {
// 获取平台默认的字符集
System.out.println(System.getProperty("file.encoding")); //UTF-8
String name = "哈哈haha 123";
// 使用平台默认的字符集编码
String ret1 = URLEncoder.encode(name);
System.out.println(ret1); //%E5%93%88%E5%93%88haha+123
// 使用指定字符集编码
String ret2 = URLEncoder.encode(name, "UTF-8");
System.out.println(ret2);//%E5%93%88%E5%93%88haha+123
String ret3 = URLEncoder.encode(name, "GBK");
System.out.println(ret3);//%B9%FE%B9%FEhaha+123
//解码
String msg = URLDecoder.decode(ret2,"UTF-8");
System.out.println(msg);//哈哈haha 123
}
}
打印输出:
UTF-8
%E5%93%88%E5%93%88haha+123
%E5%93%88%E5%93%88haha+123
%B9%FE%B9%FEhaha+123
哈哈haha 123