最近在使用 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/
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。
整理自网络

: https://blog.darkmi.com/2017/10/16/3964.html

本文相关评论 - 1条评论都没有呢
Post a comment now » 本文目前不可评论

No comments yet.

Sorry, the comment form is closed at this time.