在 Java 中编码 URL 查询参数 [英] Encoding URL query parameters in Java
本文介绍了在 Java 中编码 URL 查询参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何编码查询参数以在 Java 中访问 url?我知道,这似乎是一个显而易见的问题.
How does one encode query parameters to go on a url in Java? I know, this seems like an obvious and already asked question.
我不确定有两个微妙之处:
There are two subtleties I'm not sure of:
- url 上的空格应该编码为+"还是%20"?在 chrome 中,如果我输入http://google.com/foo=?bar me",chrome 会将其更改为使用 %20 编码
- 将冒号:"编码为 %3B 是否必要/正确?Chrome 没有.
注意事项:
java.net.URLEncoder.encode
似乎不起作用,它似乎是为了对表单提交的数据进行编码.例如,它将空格编码为+
而不是%20
,并编码不必要的冒号.java.net.URI
不对查询参数进行编码
java.net.URLEncoder.encode
doesn't seem to work, it seems to be for encoding data to be form submitted. For example, it encodes space as+
instead of%20
, and encodes colon which isn't necessary.java.net.URI
doesn't encode query parameters
推荐答案
java.net.URLEncoder.encode(String s, String encoding)
也有帮助.它遵循 HTML 表单编码 application/x-www-form-urlencoded
.
URLEncoder.encode(query, "UTF-8");
<小时>
另一方面,百分比编码(也称为 URL 编码) 用 %20
编码空间.冒号是一个保留字符,所以 :
在编码后仍然是一个冒号.
On the other hand, Percent-encoding (also known as URL encoding) encodes space with %20
. Colon is a reserved character, so :
will still remain a colon, after encoding.
这篇关于在 Java 中编码 URL 查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文