Encoding and decoding a URL string in Java

URL encoding is very essential in the Java web because it protects the user and avoids vulnerable attacks like SQL injection. How can you safely encode a URL or form passed through a Servlet, or a program that runs on a web server.

Java provides the URLEncoder class that has the encode(). This method  encodes a String.

You also need a means of decoding. The URLDecoder class has the decode() to decode the String encoded with URLEncoder.

Example:

import java.io.UnsupportedEncodingException; 

public class Encode_Decode {

public static void main(String[] args) {
String url = "This is a test_[]< > ()!#^$@%~&*";
try {
String urlencode = java.net.URLEncoder.encode(url, "UTF-8");
System.out.println("Encoding: "+urlencode);
String urldecode = java.net.URLDecoder.decode(urlencode, "UTF-8");
System.out.println("Decoding: "+urldecode);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Output

Coding: This+is+a+test_%5B%5D%3C%3E%28%29%21%23%5E%24%40%25%7E%26*
Decode: This is a test_[]< > ()!#^$@%~&*
In this program, the String urlencode variable is passed as an argument in the URLEncoder.encoder.encoder method and then the result is displayed. Then, it decodes the variable encoded with  URLDecoder.decode and displays the decoded url.

For more information, I recommend reading the Java documentation for URLEncoder and URLDecoder.