How to Decode URLs in Java

URL decoding is used to parse query strings or form parameters. HTML form parameters are encoded using application/x-www-form-urlencoded MIME type. They must be decoded before using in the application. Similarly, Any query string passed in the URL is also encoded and must be decoded before use.

If you’re working with a web framework like Spring, Dropwizard, or Play, then query strings and form parameters are already decoded by these frameworks. But if you’re building standalone applications without any framework then you can decode URL or form parameters using Java’s URLDecoder utility class.

URL Decoding query strings or form parameters in Java

The following example demonstrates how to perform URL decoding in Java -

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

public class URLDecodingExample {

    // Decodes a URL encoded string using `UTF-8`
    public static String decodeValue(String value) {
        try {
            return URLDecoder.decode(value, StandardCharsets.UTF_8.toString());
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException(ex.getCause());
        }
    }

    public static void main(String[] args) {
        String encodedValue = "Hell%C3%B6%20W%C3%B6rld%40Java";

        // Decoding the URL encoded string
        String decodedValue = decodeValue(encodedValue);

        System.out.println(decodedValue);
    }
}
# Output
Hellö Wörld@Java

Our example uses UTF-8 encoding for decoding the URLs. You should always use UTF-8 to avoid incompatibilities with other systems. That is what the world wide web consortium recommends.

Also Read: How to URL Encode a String in Java

Footnotes