URLEncoder
java.net.URLEncoder Example
In this example we shall show you how to make use of URLEncoder
class. URLEncoder
is a utility class for HTML form encoding, contains static methods for converting a string to the application/x-www-form-urlencoded MIME format. This class is very useful to encode URL query string values.
When encoding a string, the following rules apply:
- The alphanumeric characters “a” through “z”, “A” through “Z” and “0” through “9” remain the same.
- The special characters “.”, “-“, “*”, and “_” remain the same.
- The space character ” ” is converted into a plus sign “+”.
- All other characters are unsafe and are first converted into one or more bytes using some encoding scheme. Then each byte is represented by the 3-character string “%xy”, where xy is the two-digit hexadecimal representation of the byte.
Below example shows how to encode URL content in java using URLEncoder
.
Example:
URLEncoderTest.javaimport java.io.UnsupportedEncodingException; import java.net.URLEncoder; /** * @author ashraf_sarhan * */ public class URLEncoderTest { /** * The main method. * * @param args the arguments */ public static void main(String[] args) { try { String string = "The string ü@foo-bar"; String encodedString = URLEncoder.encode(string, "UTF-8"); System.out.println("Encoded String: " + encodedString); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } }
In the above example using UTF-8 as the encoding scheme, the string “The string ü@foo-bar” would get converted to “The+string+%C3%BC%40foo-bar” because in UTF-8 the character ü is encoded as two bytes C3 (hex) and BC (hex), and the character @ is encoded as one byte 40 (hex).
Tip
- Method
encode(String s)
has been deprecated withencode(String s, String enc)
now being the only available method. - The recommended encoding scheme to use is UTF-8. However, for compatibility reasons, if an encoding is not specified, then the default encoding of the platform is used.
3. Download the Source Code of this example:
This was an example of how to use URLEncoder
class.
Download
You can download the full source code of this example here: java.net.URLEncoder Example Code
You can download the full source code of this example here: java.net.URLEncoder Example Code