Encoding URL query parameters in Java
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:
- Should spaces be encoded on the url as "+" or as "%20"? In chrome if I type in "http://google.com/foo=?bar me" chrome changes it to be encoded with %20
- Is it necessary/correct to encode colons ":" as %3B? Chrome doesn't.
Notes:
-
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
Solution 1:
java.net.URLEncoder.encode(String s, String encoding)
can help too. It follows the HTML form encoding application/x-www-form-urlencoded
.
URLEncoder.encode(query, "UTF-8");
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.
Solution 2:
EDIT: URIUtil
is no longer available in more recent versions, better answer at Java - encode URL or by Mr. Sindi in this thread.
URIUtil
of Apache httpclient is really useful, although there are some alternatives
URIUtil.encodeQuery(url);
For example, it encodes space as "+" instead of "%20"
Both are perfectly valid in the right context. Although if you really preferred you could issue a string replace.