1.URLEncoder.encode(String s, String enc)
使用指定的編碼機制將字符串轉換為 application/x-www-form-urlencoded 格式
URLDecoder.decode(String s, String enc)
使用指定的編碼機制對 application/x-www-form-urlencoded 字符串解碼。
2.發送的時候使用URLEncoder.encode編碼,接收的時候使用URLDecoder.decode解碼,都按指定的編碼格式進行編碼、解碼,可以保證不會出現亂碼
3.主要用來http get請求不能傳輸中文參數問題。http請求是不接受中文參數的。
這就需要發送方,將中文參數encode,接收方將參數decode,這樣接收方就能收到准確的原始字符串了。
public static void main(String[] args) { String chinas= "中文編碼解碼"; try{ String encoderString = URLEncoder.encode(chinas,"utf-8"); System.out.println(encoderString); String decodedString = URLDecoder.decode(encoderString,"utf-8"); System.out.println(decodedString); }catch (UnsupportedEncodingException e){ e.printStackTrace(); } } 輸出: %E4%B8%AD%E6%96%87%E7%BC%96%E7%A0%81%E8%A7%A3%E7%A0%81 中文編碼解碼