Using Java’s URLEncoder

We developers really should heed the warnings of deprecations.

Java’s URLEncoder.encode(String); throws the deprecated warning, encouraging us to use URLEncoder.encode(String,String);. I use this tool to encode the special characters in parameters on an URL to prevent a misunderstanding with a server.

Want to finally do the right thing and use that method? Here’s what you need to know!

The second parameter sets the Charset of the encoder. It takes the definition as a String of any of these values1:

Charset

Description

US-ASCIISeven-bit ASCII, a.k.a. ISO646-US,
a.k.a. the Basic Latin block of the Unicode character set
ISO-8859-1  ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1
UTF-8Eight-bit UCS Transformation Format
UTF-16BESixteen-bit UCS Transformation Format,
big-endian byte order
UTF-16LESixteen-bit UCS Transformation Format,
little-endian byte order
UTF-16Sixteen-bit UCS Transformation Format,
byte order identified by an optional byte-order mark

Answer

The simple adjustment would be to pass “UTF-8” into the method:

String encodedUrlParam = URLEncoder.encode(params, "UTF-8");

Of course you can externalize the appropriate charset to constant. Or setup an internal util class constructed and configured at runtime with Spring’s IoC, which the rest of your application will use instead of the URLEncoder.

More Information

1. JavaDoc on Charset