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:
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 parametersjava.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.