Search code examples
javaurl-encoding

When will java.net.URLEncoder.encode function throw UnsupportedEncodingException?


If I were to encode a string using the encode method of the URLEncoder class, when will it throw the UnsupportedEncodingException?

String encodedString = URLEncoder.encode(myString, "UTF-8");

I have read the documentation which reads,

Throws: UnsupportedEncodingException - If the named encoding is not supported

So, will this ever happen to my code if I always use "UTF-8"?


Solution

  • You should be fine with UTF-8, it depends on JVM installed on computer, where final application will run. Anyhow UTF-8 is now supported by java.

    You can use static constants in StandardCharsets class:

    URLEncoder.encode("Your string", StandardCharsets.UTF_8.toString());