前言
前后端直接傳輸數據進行交互不就行了嗎,為什么還要進行編碼解碼?正常情況下直接交互沒問題,但當有類似以下情況出現時就需要進行編碼再進行傳輸:
1、編碼格式難以統一,導致數據交互過程出現中文亂碼等問題;
2、進行HTTP GET請求,參數是跟在URl上面,當參數的值有“/”、“&”等特殊字符時,將導致程序報錯;
3、進行HTTP POST請求,參數放在請求體里自由穿梭在前、后端,但人在江湖飄哪有不挨刀,程序員總是要經歷一些奇奇怪怪的bug才能變強變禿,比如最近我們項目就碰到一個奇怪的bug,兩邊的編碼格式已經一致,前端發送的是英文、半角狀態下的密碼字符串(字符串里有個美元符號),后端接到的數據中,半角狀態的美元符號變成了全角狀態的“$”,其他的字符正常,導致后續業務操作出現問題,而這兩個狀態下的沒有符號變化不是很大,乍一看沒看出來,導致這個bug我們排查了好久才解決...
本文記錄多種常用的js、java編碼解碼方法
常用方法
URL編碼解碼
java
/* javaURL編碼解碼,需要引入這兩個JDK自帶net包里面的類 import java.net.URLDecoder; import java.net.URLEncoder; */ //URL編碼 String encode = URLEncoder.encode("HuanZi!#123.qch@qq.com/fdfd", "UTF-8"); System.out.println(encode);
//HuanZi%21%23123.qch%40qq.com%2Ffdfd
//URL解碼 String decode = URLDecoder.decode(encode, "UTF-8"); System.out.println(decode); //HuanZi!#123.qch@qq.com/fdfd
js
/* jsURL編碼解碼,我們使用encodeURIComponent、decodeURIComponent就可以了,它默認使用 UTF-8 */ //URL編碼 let encode = encodeURIComponent ("HuanZi!#123.qch@qq.com/fdfd"); console.log(encode); //HuanZi!%23123.qch%40qq.com%2Ffdfd //URL解碼 let decode = decodeURIComponent(encode); console.log(decode); //HuanZi!#123.qch@qq.com/fdfd
Base64編碼解碼
java
需要先maven引入apache提供的Base64工具類

<!-- Base64編碼需要 --> <dependency> <groupId>org.apache.directory.studio</groupId> <artifactId>org.apache.commons.codec</artifactId> <version>1.8</version> </dependency>
/* javaBase64編碼解碼,需要引入 import org.apache.commons.codec.binary.Base64; */ //Base64編碼 String encode1 = Base64.encodeBase64String("HuanZi!#123.qch@qq.com/fdfd".getBytes()); System.out.println(encode1); //SHVhblppISMxMjMucWNoQHFxLmNvbS9mZGZk //Base64解碼 String decode1 = new String(Base64.decodeBase64(encode1)); System.out.println(decode1); //HuanZi!#123.qch@qq.com/fdfd
js
先創建Base64工具對象(參考MDN的Base64編碼和解碼思路之一:https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#Solution_4_%E2%80%93_escaping_the_string_before_encoding_it)

let Base64 = { encode(str) { // first we use encodeURIComponent to get percent-encoded UTF-8, // then we convert the percent encodings into raw bytes which // can be fed into btoa. return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function toSolidBytes(match, p1) { return String.fromCharCode('0x' + p1); })); }, decode(str) { // Going backwards: from bytestream, to percent-encoding, to original string. return decodeURIComponent(atob(str).split('').map(function (c) { return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); }).join('')); } };
/* js Base64編碼解碼,需要先創建Base64工具對象 */ //Base64編碼 let encoded = Base64.encode("HuanZi!#123.qch@qq.com/fdfd"); console.log(encoded); //SHVhblppISMxMjMucWNoQHFxLmNvbS9mZGZk //Base64解碼 let decoded = Base64.decode(encoded); console.log(decoded); //HuanZi!#123.qch@qq.com/fdfd
后記
一定要保證前后端編碼、解碼一致,否則會造成一端編碼,另一端解碼失敗的嚴重后果
更多方法持續更新中...