代碼:
public static void main(String[] args) throws UnsupportedEncodingException {
String urlStr = "http://172.168.1.1192.168.1.1:8888/store/get?id=dc2-80d";
String urlStrEncode = URLEncoder.encode(urlStr, "utf-8" );
String urlStrDecode = URLDecoder.decode(urlStrEncode, "utf-8");
System.out.println("urlStrEncode = " + urlStrEncode);
System.out.println("urlStrDecode = " + urlStrDecode);
// 將普通字符串轉(zhuǎn)換成 application/x-www-form-urlencoded字符串
String str = URLEncoder.encode("默默前行", "UTF-8");
System.out.println("str = " + str);
// 將application/x-www-form-urlencoded字符串轉(zhuǎn)換成普通字符串
String keyWord = URLDecoder.decode("%E9%BB%98%E9%BB%98%E5%89%8D%E8%A1%8C", "UTF-8");
System.out.println("keyWord = " + keyWord);
}
輸出:
urlStrEncode = http%3A%2F%2F172.168.1.1192.168.1.1%3A8888%2Fstore%2Fget%3Fid%3Ddc2-80d
urlStrDecode = http://172.168.1.1192.168.1.1:8888/store/get?id=dc2-80d
str = %E9%BB%98%E9%BB%98%E5%89%8D%E8%A1%8C
keyWord = 默默前行
"%E9%BB%98%E9%BB%98%E5%89%8D%E8%A1%8C"
這些字符就是applicaion/x-www-form-urlencoded MIME字符串谈跛。
當(dāng)URL地址里包含非西歐字符的字符串時(shí),系統(tǒng)會(huì)將這些非西歐轉(zhuǎn)換成如圖所示的特殊字符串,那么編碼過程中可能涉及將普通字符串和這種特殊字符串的相關(guān)轉(zhuǎn)換,這就是需要使用URLDecoder和URLEncoder類。
參考資料:https://blog.csdn.net/y1991024/article/details/62890221