Say I have a URL
http://example.com/query?q=
and I have a query entered by the user such as:
random word £500 bank $
I want the result to be a properly encoded URL:
http://example.com/query?q=random%20word%20%A3500%20bank%20%24
What’s the best way to achieve this? I tried URLEncoder and creating URI/URL objects but none of them come out quite right.
URLEncoderis 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=.When you’re still not on Java 10 or newer, then use
StandardCharsets.UTF_8.name()as charset argument, or when you’re still not on Java 7 or newer, then use"UTF-8".Note that spaces in query parameters are represented by
+, not%20, which is legitimately valid. The%20is usually to be used to represent spaces in URI itself (the part before the URI-query string separator character?), not in query string (the part after?).Also note that there are three
encode()methods. One withoutCharsetas second argument and another withStringas second argument which throws a checked exception. The one withoutCharsetargument is deprecated. Never use it and always specify theCharsetargument. The javadoc even explicitly recommends to use the UTF-8 encoding, as mandated by RFC3986 and W3C.See also: