URLEncoder.encode 和 URLDecoder.decode 處理url的特殊參數


在使用 url 的 queryString 傳遞參數時,因為參數的值,被DES加密了,而加密得到的是 Base64的編碼字符串,類似於:

za4T8MHB/6mhmYgXB7IntyyOUL7Cl++0jv5rFxAIFVji8GDrcf+k8g==

顯然 這里面含有了 特殊字符: / + = 等等,如果直接通過url 來傳遞該參數:

url = "xxxxx?param=" + "za4T8MHB/6mhmYgXB7IntyyOUL7Cl++0jv5rFxAIFVji8GDrcf+k8g==";

那么在服務端獲得 param 會變成類似於下面的值:

"za4T8MHB/6mhmYgXB7IntyyOUL7Cl  0jv5rFxAIFVji8GDrcf k8g=="

我們看到 三個 + 號消失了。

其原因就是:如果url參數值含有特殊字符時,需要使用 url 編碼。

url = "xxxxx?param=" + URLEncoder.encode("xxx", "utf-8");

然后服務端獲取時:

String param = URLDecoder.decode(param, "utf-8");

這樣才能獲得正確的值:"za4T8MHB/6mhmYgXB7IntyyOUL7Cl++0jv5rFxAIFVji8GDrcf+k8g=="

其實 js 中也有類似功能的函數:

參見:js中的三個編碼函數:escape,encodeURI,encodeURIComponent

注意事項

URLEncoder should be the way to go. You only need to keep in mind to encode only the individual query string parameter name and/or value, not the entire URL, for sure not the query string parameter separator character & nor the parameter name-value separator character =

String q = "random word 攏500 bank $";
String url = "http://example.com/query?q=" + URLEncoder.encode(q, "UTF-8");

URLEncoder 必須 僅僅 編碼 參數 或者參數的值,不能編碼整個 url,也不能一起對 param=value 進行編碼。而是應該: param=URLEncode(value, "utf-8")

或者 URLEncode(param, "utf-8")=URLEncode(value, "utf-8")

因為 url 中的 & 和 = 他們是作為參數之間 以及 參數和值之間的分隔符的。如果一起編碼了,就無法區分他們了。

進一步參考文檔:

https://www.talisman.org/~erlkonig/misc/lunatech%5Ewhat-every-webdev-must-know-about-url-encoding/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM