Tools Coverters

A Deep Dive into URL Encoding with Java

A Deep Dive into URL Encoding with Java Image

Published Date: September 9, 2022

Updated Date: September 9, 2022

In order to encode a string or a URL in Java, you can use the JavaURLEncoder method.

Java provides a URLEncoder class for encoding any string or URL. By default, the URLEncoder class in Java uses the UTF-8 format.

An important note: When you are encoding any URL in JAVA, do not encode the entire URL rather just encode the query string.

How to encode a string or a URL in Java using the URLEncoder class

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.io.UnsupportedEncodingException;

class URLEncodingExample {

    // Method to encode a string value using `UTF-8` encoding scheme
    private static String encodeValue(String value) {
        try {
            return URLEncoder.encode(value, StandardCharsets.UTF_8.toString());
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException(ex.getCause());
        }
    }

    public static void main(String[] args) {
        String baseUrl = "https://www.google.com/search?q=";

        String query = "Tööls Cönverters URLEncoder@Java";
        String encodedQuery = encodeValue(query); // Encoding a query string

        String completeUrl = baseUrl + encodedQuery;
        System.out.println(completeUrl);
    }
}

Output:

# Output
https://www.google.com/search?q=T%C3%B6%C3%B6ls%20C%C3%B6nverters%20xyz%20URLEncoder%40Java

You can also click this URL encoded link and see the results yourself Tööls Cönverters xyz URLEncoder@Java

Another interesting to note about the URLEncoder class in Java is that it encodes the space character as a + v/s other languages that encode the space character into %20. You can check out this StackOverflow discussion to understand the reasoning for character encoding of space as + v/s %20

If you note the code we wrote above

URLEncoder.encode(value, StandardCharsets.UTF_8.toString())

We are passing the format in which we want the encoding to happen. Here we are exclusively using UTF-8 format. You can choose to add another format that the function supports.

An important thing to note is that if you are URL Encoding in JAVA, and you pass in a format that is not supported or you try to create your own word as the 2nd argument to encode. You will receive an UnsupportedEncodingException from the compiler.

Related Encoding techniques:

There are many applications that require you to encode your URL into a format that the systems can understand. If you wish to encode a URL, check out our free online URL Encoder.

Some systems communicate with encoded URLs, so you may need to decode a URL. If you want to decode a URL online, we have our free online URL Decoder.