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.


import 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) {


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).


  • Method encode(String s) has been deprecated with encode(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.

You can download the full source code of this example here: java.net.URLEncoder Example Code

Ashraf Sarhan

Ashraf Sarhan is a passionate software engineer, an open source enthusiast, has a Bsc. degree in Computer and Information Systems from Alexandria University. He is experienced in building large, scalable and distributed enterprise applications/service in multiple domains. He also has a keen interest in JavaEE, SOA, Agile and Big Data technologies.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button