最近在使用 url 的 queryString 傳遞參數(shù)時(shí),因?yàn)閰?shù)的值(注意是參數(shù)的值被加密),被DES加密了,而加密得到的是 Base64的編碼字符串。
類似于:
za4T8MHB/6mhmYgXB7IntyyOUL7Cl++0jv5rFxAIFVji8GDrcf+k8g==
顯然 這里面含有了 特殊字符: / + = 等等,如果直接通過(guò)url 來(lái)傳遞該參數(shù):
url = "xxxxx?param=" + "za4T8MHB/6mhmYgXB7IntyyOUL7Cl++0jv5rFxAIFVji8GDrcf+k8g==";
那么在服務(wù)端獲得 param 會(huì)變成類似于下面的值:
"za4T8MHB/6mhmYgXB7IntyyOUL7Cl 0jv5rFxAIFVji8GDrcf k8g=="
我們看到 三個(gè) + 號(hào)消失了。
其原因就是:如果url參數(shù)值含有特殊字符時(shí),需要使用 url 編碼。
url = "xxxxx?param=" + URLEncoder.encode("xxx", "utf-8");
然后服務(wù)端獲取時(shí):
String param = URLDecoder.decode(param, "utf-8");
這樣才能獲得正確的值:"za4T8MHB/6mhmYgXB7IntyyOUL7Cl++0jv5rFxAIFVji8GDrcf+k8g=="
注意事項(xiàng):
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 必須 僅僅 編碼 參數(shù) 或者參數(shù)的值,不能編碼整個(gè) url,也不能一起對(duì)param=value進(jìn)行編碼。
而是應(yīng)該: param=URLEncode(value, "utf-8")
或者URLEncode(param, "utf-8")=URLEncode(value, "utf-8")
因?yàn)?url 中的& 和= 他們是作為參數(shù)之間 以及 參數(shù)和值之間的分隔符的。如果一起編碼了,就無(wú)法區(qū)分他們了。