EN
Java - decodeURIComponent equivalent in JavaScript
6
points
In this article, we would like to show how to get JavaScript decodeURIComponent
function equivalent in Java.
Using Java, sometimes it is necessary to decode some data to send inside URL. JavaScript provides well known decodeURIComponent
function.
To get the same effect in Java it is necessary to do the following code:
// import java.net.URLDecoder;
String text = "Hi!%20How%20are%20you%3F%20Dangerous%20characters%3A%20%3F%23%26";
String decodedText = URLDecoder.decode(text, StandardCharsets.UTF_8.name());
System.out.println(decodedText); // Hi! How are you? Dangerous characters: ?#&
Output:
Hi! How are you? Dangerous characters: ?#&
Note: check
encodeURIComponent
function Java equivalent here.
Reusable code example
Program.java
file:
package com.dirask.examples;
import java.io.UnsupportedEncodingException;
public class Program {
public static void main(String[] args) {
String text = "Hi!%20How%20are%20you%3F%20Dangerous%20characters%3A%20%3F%23%26";
String decodedText = URIDecoder.decodeURIComponent(text);
System.out.println(decodedText);
}
}
Output:
Hi! How are you? Dangerous characters: ?#&
URIDecoder.java
file:
package com.dirask.examples;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
public class URIDecoder {
private static final String CHARSET = StandardCharsets.UTF_8.name();
public static String decodeURIComponent(String text) {
try {
return URLDecoder.decode(text, CHARSET);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
}