URL编码原因
一般来说,URL只能使用英文字母、阿拉伯数字和某些标点符号,不能使用其他文字和符号。比如,世界上有英文字母的网址 “http://www.abc.com”,但是没有希腊字母的网址“http://www.aβγ.com”(读作阿尔法-贝塔-伽玛.com)。这是 因为网络标准RFC 1738 做了硬性规定:
"…Only alphanumerics [0-9a-zA-Z], the special characters " − . + ! ∗ ′ ( ) , " [ n o t i n c l u d i n g t h e q u o t e s − e d ] , a n d r e s e r v e d c h a r a c t e r s u s e d f o r t h e i r r e s e r v e d p u r p o s e s m a y b e u s e d u n e n c o d e d w i t h i n a U R L . " “ 只 有 字 母 和 数 字 [ 0 − 9 a − z A − Z ] 、 一 些 特 殊 符 号 “ -_.+!*'()," [not including the quotes - ed], and reserved characters used for their reserved purposes may be used unencoded within a URL." “只有字母和数字[0-9a-zA-Z]、一些特殊符号“ −.+!∗′(),"[notincludingthequotes−ed],andreservedcharactersusedfortheirreservedpurposesmaybeusedunencodedwithinaURL."“只有字母和数字[0−9a−zA−Z]、一些特殊符号“-_.+!*’(),”[不包括双引号]、以及某些保留字,才可以不经过编码直接用于 URL。”
这意味着,如果URL中有汉字,就必须编码后使用。
代码实现编码和解码
public class Test {
public static void main(String[] args) {
String str = "https://baike.baidu.com/item/刘亦菲/136156";
String encode = "UTF-8";
System.out.println("原始字符串:" + str);
System.out.println("编码方式:" + encode);
String result = getURLEncoderString(str, encode);
System.out.println("编码之后的字符串:" + result);
result = getURLDecoderString(str, encode);
System.out.println("解码之后的字符串:" + result);
}
/**
* 编码
*
* @param str 准备编码的字符串
* @param encode 编码方式
* @return 完成编码的字符串
*/
public static String getURLEncoderString(String str, String encode) {
String result = null;
try {
result = URLEncoder.encode(str, encode);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
/**
* 解码
*
* @param str 已经编码的字符串
* @param encode 解码方式
* @return 完成解码的字符串
*/
public static String getURLDecoderString(String str, String encode) {
String result = null;
try {
result = URLDecoder.decode(str, encode);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
}
结果:
原始字符串:https://baike.baidu.com/item/刘亦菲/136156
编码方式:UTF-8
编码之后的字符串:https%3A%2F%2Fbaike.baidu.com%2Fitem%2F%E5%88%98%E4%BA%A6%E8%8F%B2%2F136156
解码之后的字符串:https://baike.baidu.com/item/刘亦菲/136156