Java:URLEncoder、URLDecoder、Base64编码与解码
生活随笔
收集整理的這篇文章主要介紹了
Java:URLEncoder、URLDecoder、Base64编码与解码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. URL
主要用來http get請求url不能傳輸中文參數問題。http請求是不接受中文參數的
1.1 URLEncoder編碼
使用指定的編碼機制將字符串轉換為 application/x-www-form-urlencoded 格式
對String編碼時,使用以下規則:
1.2 URLDecoder解碼
使用指定的編碼機制對 application/x-www-form-urlencoded 字符串解碼。
1.3 舉例
public static void main(String[] args) throws UnsupportedEncodingException {String str = "編碼測試+-./&=a=1*%123";String charset = "utf-8";System.out.println("urlEncoder編碼數據: " + str);String encode = URLEncoder.encode(str, charset);System.out.println("編碼結果: " + encode);String decode = URLDecoder.decode(encode, charset);System.out.println("解碼結果: " + decode);}urlEncoder編碼數據: 編碼測試+-./&=a=1*%123 編碼結果: %E7%BC%96%E7%A0%81%E6%B5%8B%E8%AF%95%2B-.%2F%26%3Da%3D1*%25123 解碼結果: 編碼測試+-./&=a=1*%1232. Base64
在網絡中傳輸數據都是使用ascii方式傳輸。對于一些圖片、視頻等數據,可能就會被編碼成ascii中不可見部分的編碼。網絡中不同的路由設備處理方式不同,有可能就會把這部分數據弄丟了。為了保證數據傳輸的正確性,可以使用Base64編碼將這些不可見數據編碼成可見數據。
由于某些系統中只能使用ASCII字符。Base64就是用來將非ASCII字符的數據轉換成ASCII字符的一種方法
2.1 Base64編碼
Base64.getEncoder().encode(str.getBytes())
2.2 Base64解碼
Base64.getDecoder().decode
2.3 舉例
public static void main(String[] args) throws UnsupportedEncodingException {String str = "編碼測試+-./&=a=1*%123";String charset = "utf-8";System.out.println("base64編碼數據: " + str);String encode = new String(Base64.getEncoder().encode(str.getBytes()));System.out.println("編碼結果: " + encode);String decode = new String(Base64.getDecoder().decode(encode));System.out.println("解碼結果: " + decode);}base64編碼數據: 編碼測試+-./&=a=1*%123 編碼結果: 57yW56CB5rWL6K+VKy0uLyY9YT0xKiUxMjM= 解碼結果: 編碼測試+-./&=a=1*%123總結
以上是生活随笔為你收集整理的Java:URLEncoder、URLDecoder、Base64编码与解码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据竞赛:如何小号作弊
- 下一篇: 详解 Java NIO