JAVA--MIME编码

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你这个橘子不要皮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值