URLDecoder和URLEncoder用于完成普通字符串 和 application/x-www-form-urlencoded MIME 字符串之间的相互转换。
用法很简单,直接看代码吧。
package pingmujietu;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
public class EncoderAndDecoder {
public static void main(String[] args) {
try {
// 编码,不同编码格式编码后的结果不同
String str = URLEncoder.encode("中国", "UTF-8");
System.out.println(str);
String str2 = URLEncoder.encode("中国", "GBK");
System.out.println(str2);
// 解码,需用对应的编码格式解码,否则会乱码
String str3 = URLDecoder.decode("%E4%B8%AD%E5%9B%BD", "UTF-8");
System.out.println(str3);
String str4 = URLDecoder.decode("%D6%D0%B9%FA", "GBK");
System.out.println(str4);
String str5 = URLDecoder.decode("%D6%D0%B9%FA", "UTF-8");
System.out.println(str5);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
输出如下:
%E4%B8%AD%E5%9B%BD
%D6%D0%B9%FA
中国
中国
?й?