用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:
- 是否应将空格编码为+或%20?在Chrome中,如果我输入http://google.com/foo=?bar mechrome,则将其更改为使用%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屋!
查看全文