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

猜你喜欢

转载自blog.csdn.net/tb9125256/article/details/81416793
今日推荐