In Java Examples, when using the GET method, parameter names and their values get submitted on the URL string after a question mark. Different parameter name/value pairs are separated by ampersands.
Usually, parameters are accessed from a request in an already decoded format (via request.getParameter()
), so no decoding is necessary.
However, occasionally certain situations arise where you need to decode a string that has been URL encoded (for instance, by the URLEncoder.encode(String s, String encoding)
method or the javascript escape()
function).
Java code:
package crunchify.com.tutorials; import java.net.URLDecoder; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; /** * @author Crunchify.com * */ public class CrunchifyEncodeDecodeExample { public static void main(String[] args) throws Exception { String crunchifyValue1 = "This is a simple Example from Crunchify"; // Use StandardCharsets String ecodedValue1 = URLEncoder.encode(crunchifyValue1, StandardCharsets.UTF_8.name()); String decodedValue1 = URLDecoder.decode(ecodedValue1, StandardCharsets.UTF_8.name()); System.out.println("crunchifyValue1 after encoding => " + ecodedValue1); System.out.println("crunchifyValue1 after decoding (Original Value): => " + decodedValue1); String crunchifyValue2 = "Hello There, We started accepting Guest-Posts on Crunchify..."; // Or directly provide UTF-8 String encodedValue2 = URLEncoder.encode(crunchifyValue2, "UTF-8"); String decodedValue2 = URLDecoder.decode(encodedValue2, "UTF-8"); System.out.println("\ncrunchifyValue2 after encoding => " + encodedValue2); System.out.println("crunchifyValue2 after decoding (Original Value) => " + decodedValue2); } }
Other must read:
- Java Tutorial: How to Create RESTful Java Client using Apache HttpClient – Example
- How to use AJAX, jQuery in Spring Web MVC (.jsp) – Example
Console Output:
crunchifyValue1 after encoding => This+is+a+simple+Example+from+Crunchify crunchifyValue1 after decoding (Original Value): => This is a simple Example from Crunchify crunchifyValue2 after encoding => Hello+There%2C+We+started+accepting+Guest-Posts+on+Crunchify... crunchifyValue2 after decoding (Original Value) => Hello There, We started accepting Guest-Posts on Crunchify...
URL encoding is required much more often than URL decoding, since decoding usually takes place automatically during calls the request.getParameter()
.
However, it is good to know that URLDecoder.decode()
exists for the occasional situation where it is needed.