最近在使用 url 的 queryString 傳遞參數時,因為參數的值,被DES加密了,而加密得到的是 Base64的編碼字符串
類似于:
1
|
za4T8MHB/6mhmYgXB7IntyyOUL7Cl++0jv5rFxAIFVji8GDrcf+k8g== |
顯然 這里面含有了 特殊字符: / + = 等等,如果直接通過url 來傳遞該參數:
1
|
url = "xxxxx?param=" + "za4T8MHB/6mhmYgXB7IntyyOUL7Cl++0jv5rFxAIFVji8GDrcf+k8g==" ; |
那么在服務端獲得 param 會變成類似于下面的值:
1
|
"za4T8MHB/6mhmYgXB7IntyyOUL7Cl 0jv5rFxAIFVji8GDrcf k8g==" |
我們看到 三個 + 號消失了。
其原因就是:如果url參數值含有特殊字符時,需要使用 url 編碼。
1
|
url = "xxxxx?param=" + URLEncoder.encode( "xxx" , "utf-8" ); |
然后服務端獲取時:
1
|
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 =
1
2
|
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/
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。