Java中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=="

注意事項:

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.jb51.net/article/109017.htm

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章