您的位置:首页 > 理论基础 > 计算机网络

js与java对http参数含有特殊字符的传递处理

2016-08-29 19:38 411 查看
http://www.cnblogs.com/digdeep/p/5580959.html

在使用 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/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: