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
- value – String for encoding.
- encoding – character encoding.
The encode()
method translates a string into application/x-www-form-urlencoded
format using a specific encoding scheme.
[pullquote align=”normal”]Note: The World Wide Web Consortium Recommendation states that UTF-8
should be used. Not doing so may introduce incompatibilities. [/pullquote]
Let’s write a unit test for our method:
public class JavaEncodeExampleTest {
String expectedURL="https://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://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://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.