URLDecoder 和 URLEncoder 对中文字符进行编码和解码

转载自:https://blog.csdn.net/justloveyou_/article/details/57156039

URLDecoder 和 URLEncoder 用于完成普通字符串和application/x-www-form-urlencoded MIME 字符串之间的相互转换

URLDecoder/URLEncoder 使用场景概述

什么是application/x-www-form-urlencoded MIME 字符串

浏览器根据请求的URL生成相应的请求报文发送给服务器,在这个过程中,如果浏览器的地址栏中所输入的URL包含中文字符时,浏览器首先会将这些中文字符进行编码然后再发送给服务器,实际上,这就是将中文字符转为application/x-www-form-urlencoded MIME字符串,如下图:
在这里插入图片描述
更确切来说,当URL中包含非西欧字符的字符串时,浏览器都会将这些非西欧字符串转换成application/x-www-form-urlencoded MIME字符串。

在开发过程中,涉及将普通字符串和这种特殊字符串的相关转换,就需要使用URLDecoder 和 URLEncoder 类进行实现

  • URLDecoder类包含一个decode(String s, String enc)静态方法,可以将application/x-www-form-urlencoded MIME 字符串转为普通字符串
  • URLEncoder类包含一个encode(String s, String enc)静态方法,可以将普通字符串转为application/x-www-form-urlencoded MIME字符串

eg:

import java.net.URLDecoder;
import java.net.URLEncoder;

public class URLDecoderTest {
    public static void main(String[] args) throws Exception{
        System.out.println("采用UTF-8字符集进行解码:");
        String str1 = URLDecoder.decode("%E4%BD%A0%E5%A5%BD%E5%91%80", "utf-8");
        System.out.println(str1);
        System.out.println("采用GBK字符集进行解码:");
        str1 = URLDecoder.decode("%E4%BD%A0%E5%A5%BD%E5%91%80", "GBK");
        System.out.println(str1);

        System.out.println("\n采用utf-8字符集进行编码:");
        String str2 = URLEncoder.encode("深圳大学", "utf-8");
        System.out.println(str2);
        System.out.println("采用GBK字符集进行编码:");
        str2 = URLEncoder.encode("深圳大学", "GBK");
        System.out.println(str2);
    }
}

运行结果:

采用UTF-8字符集进行解码:
你好呀
采用GBK字符集进行解码:
浣犲ソ鍛�

采用utf-8字符集进行编码:
%E6%B7%B1%E5%9C%B3%E5%A4%A7%E5%AD%A6
采用GBK字符集进行编码:
%C9%EE%DB%DA%B4%F3%D1%A7

特别的,仅包含西欧字符的普通字符串和application/x-www-form-urlencoded MIME字符串无需转换,而包含中文字符的普通字符串需要转换,转换方法时每个中文字符占两个字节,每个字节可以转换为2个十六进制的数字,所以每个中文字符将转换成“%xx%xx”的形式。

当然,采用不同字符集进行转换时,每个中文字符对应字节数并不完全相同,使用URLDecoder和URLEncoder进行转换时需要指定字符集,相同字符串使用不同字符集进行解码或编码将产生不一样的结果,如上述例子所示。

猜你喜欢

转载自blog.csdn.net/weixin_39663138/article/details/86664246