java.net.URLEncoder.encode(String) is deprecated, what should I use instead?
I get the following warning when using
warning: [deprecation] encode(java.lang.String) in java.net.URLEncoder has been deprecated
What should I be using instead?
Asked by: Michael856 | Posted: 23-01-2022
Use the other
encode method in URLEncoder:
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:
Answered by: Adrian574 | Posted: 24-02-2022
System.out.println( URLEncoder.encode( "urlParameterString", java.nio.charset.StandardCharsets.UTF_8.toString() ) );
You should use:
Answered by: Edgar834 | Posted: 24-02-2022
Use the class URLEncoder:
URLEncoder.encode(String s, String enc)
s - String to be translated.
enc - The name of a supported character encoding.
US-ASCII Seven-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-8 Eight-bit UCS Transformation Format
UTF-16BE Sixteen-bit UCS Transformation Format, big-endian byte order
UTF-16LE Sixteen-bit UCS Transformation Format, little-endian byte order
UTF-16 Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark
Answered by: Sydney446 | Posted: 24-02-2022
import java.net.URLEncoder; String stringEncoded = URLEncoder.encode( "This text must be encoded! aeiou Ã¡Ã©ÃÃ³Ãº Ã±, peace!", "UTF-8");
The first parameter is the String to encode; the second is the name of the character encoding to use (e.g., UTF-8).Answered by: Melissa403 | Posted: 24-02-2022
The usage of
org.apache.commons.httpclient.URI is not strictly an issue; what is an issue is that you target the wrong constructor, which is depreciated.
new URI( [string] );
Will indeed flag it as depreciated. What is needed is to provide at minimum one additional argument (the first, below), and ideally two:
escaped: true if URI character sequence is in escaped form. false otherwise.
charset: the charset string to do escape encoding, if required
This will target a non-depreciated constructor within that class. So an ideal usage would be as such:
new URI( [string], true, StandardCharsets.UTF_8.toString() );
A bit crazy-late in the game (a hair over 11 years later - egad!), but I hope this helps someone else, especially if the method at the far end is still expecting a URI, such as
As an additional reference for the other responses, instead of using "UTF-8" you can use:
which is included since Java 4 as part of the org.apache.http.protocol library, which is included also since Android API 1.Answered by: Hailey563 | Posted: 24-02-2022
Still can't find your answer? Check out these amazing Java communities for help...
Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)