Introduction to Java URL Encoding/Decoding

In this Java article, we will talk about URL encoding decoding in Java. Implementing URL encoding and decoding is a common requirement. URL encoding is the process to translate special characters from the URL based on specifications. URL decoding is opposite to the URL encoding. Let’s see how to encode/decode URL and form data in Java.

 

1. Encode The URL

You only need to encode the query string part of the URL Encoding the entire URL is hardly needed until your base URL contains the special characters. To perform the encoding we can use URLEncoder.encode() method available with JDK.

  public static String encodeData(String value) throws UnsupportedEncodingException {
  return URLEncoder.encode(value, StandardCharsets.UTF_8.name());
 }

The encode method takes following 2 parameters

  1. value – String for encoding.
  2. encoding – character encoding.

The encode() method translates a string into application/x-www-form-urlencoded format using a specific encoding scheme.

Note: The World Wide Web Consortium Recommendation states that UTF-8 should be used. Not doing so may introduce incompatibilities.

Let’s write a unit test for our method:

public class JavaEncodeExampleTest {

    String expectedURL="https://www.javadevjournal.com?secretKey=test_6H%217%26DCepBtGGx-b&name=Java+Dev+Journal&email=contact-us%40javadevjournal.com";  //final encoded URL

    @Test
    public void test_url_encoding(){

        Map<String, String> params = new HashMap<>();  //query string parameters

        params.put("name","Java Dev Journal");
        params.put("email","[email protected]");
        params.put("secretKey","test_6H!7&DCepBtGGx-b");

        String encodedURL = params.entrySet()
                              .stream()
                              .map(e->e.getKey() + "=" +encode(e.getValue()))
                              .collect(Collectors.joining("&","https://www.javadevjournal.com?",""));

        assertThat(expectedURL,is(encodedURL));
    }

    public static String encode(String value) {
        try {
            return URLEncoder.encode(value, StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {

            e.printStackTrace();
        }

        return "";
    }
}

In case you want to encode complete URL and not the query string pass the complete URL to the encode method.

 

2. Encode The URL

URL decoding in Java is opposite to what we did in the first step. Let’s decode the same URL using URLDecoder.

public void test_url_decoder() throws MalformedURLException {
    URL url =new URL("https://www.javadevjournal.com?secretKey=test_6H%217%26DCepBtGGx-b&name=Java+Dev+Journal&email=contact-us%40javadevjournal.com");
    Map<String, List> decodedParams= decodeQuery(url);
    System.out.println(decodedParams);

}

public Map<String, List> decodeQuery(URL url) {

   return Arrays.stream(url.getQuery().split("&"))
            .map(this::splitQueryParameter)
            .collect(Collectors.groupingBy(AbstractMap.SimpleImmutableEntry::getKey, LinkedHashMap::new, mapping(Map.Entry::getValue, toList())));
}

public AbstractMap.SimpleImmutableEntry<String, String> splitQueryParameter(String it) {
    final int idx = it.indexOf("=");
    final String key = idx > 0 ? it.substring(0, idx) : it;
    final String value = idx > 0 && it.length() > idx + 1 ? it.substring(idx + 1) : null;
    return new AbstractMap.SimpleImmutableEntry<>(key, decode(value));
}

private String decode(String value) {
    try {
        return URLDecoder.decode(value, StandardCharsets.UTF_8.name());
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return value;
}

While decoding the URL, make sure we are using the same schema else we might get some unpredictable results.

 

Summary

In this article, we saw URL encoding and decoding in Java. We got an understanding of the methods to encode and decode URL in Java. The source code for this article is available on the GitHub.

Manish Sharma

Manish's primary interests are Java, Spring Boot and Spring. His focus is more toward the automations and testing.Manish love travelling and when not working, he might be exploring some new destination.

Leave a Reply

avatar

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

  Subscribe  
Notify of