java.net.URLEncoder.encode(String) is deprecated, what should I use instead?

Frank Krueger picture Frank Krueger · Oct 17, 2008 · Viewed 188.3k times · Source

I get the following warning when using java.net.URLEncoder.encode:

warning: [deprecation] encode(java.lang.String)
         in java.net.URLEncoder has been deprecated

What should I be using instead?

Answer

Will Wagner picture Will Wagner · Oct 17, 2008

Use the other encode method in URLEncoder:

URLEncoder.encode(String, String)

The first parameter is the text to encode; the second is the name of the character encoding to use (e.g., UTF-8). For example:

System.out.println(
  URLEncoder.encode(
    "urlParameterString",
    java.nio.charset.StandardCharsets.UTF_8.toString()
  )
);