It is always a good practice to encode the URL or the Form parameters as it is vulnerable to attack. URLEncoder is the utility class provided by Java which can be used for HTML form encoding. The URLEncoder class converts any String into application/x-www-form-urlencoded. In this article we will learn about Java URL encode and decode using URLEncoder and URLDecoder.
During the encode process the URLEncoder applies the below rules
- The Alphabets and Numeric characters [a – z | A – Z | 0 – 9 ] remains the same after the encode
- The special characters “.”, “-“, “*”, and “_” remain the same.
- The Space character ” “ will be converted into a plus sign “+”
- All other characters are unsafe and are first converted into one or more bytes using some encoding scheme.
Java URL Encode – URLEncoder
We will be using the encode() method of the URLEncoder class to encode the url.
package com.javainterviewpoint; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; public class UrlEncoderExample { public static void main(String[] args) { // URL String url = "https://www.java.com/?name=Java Interview Point"; try { // Encoding using encode() String encodedUrl = URLEncoder.encode(url, "UTF-8"); System.out.println("Encoded Url : "+encodedUrl); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } }
Output
Encoded Url : https%3A%2F%2Fwww.java.com%2F%3Fname%3DJava+Interview+Point
- The encode() method is a static method which takes up two parameters
- The first parameter is the URL which needs to be encoded
- The second parameter is the encoding scheme which needs to be used, in our case we are using “UTF-8” encoding scheme
- In the input url which we have passed, the non-alpha numeric characters are encoded into
- colon “:” is encoded into %3A
- slash “/” is encoded into %2F
- question mark “?” is encoded into “%3F”
- equal sign is encoded into “%3D”
Java URL Decode – URLDecoder
Now lets do the vice-versa, we will be decoding the encoded url. We will be using the decode() method of the URLDecoder class to decode the url.
package com.javainterviewpoint; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; public class UrlDecoderExample { public static void main(String[] args) { // Encoded URL String encodedUrl = "https%3A%2F%2Fwww.java.com%2F%3Fname%3DJava+Interview+Point"; try { // Decoding using decode() String decodedUrl = URLDecoder.decode(encodedUrl, "UTF-8"); System.out.println("Decoded Url : "+decodedUrl); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } }
Output
Decoded Url : https://www.java.com/?name=Java Interview Point
The decode() method is also a static method which takes up two parameters
- The first parameter is the encoded url which needs to be decoded
- The second parameter is the decoding scheme, in our case we are using “UTF-8” decoding scheme
Leave a Reply