How to Decode URL content in Java ?

  • The task to the reverse of URL encoding and distinct from URL parser is called Url Decoding.
  • It is a common requirement to implement URL encoding and decoding in Java while creating crawlers or downloaders.
 Decode URL

Decode URL

The Decode URL following steps are given below,

  • The same URL can be encoded multiple times, we need to decode it until the URL cannnot be decoded further. For example, “video%252Fmp4” is the result of two encodings. Upon decoding it once, we get “video%2Fmp4”. Now the URL needs to be further decoded so that we get “video/mp4”, which is the result.
  • We use the decode method of a predefined Java class named URLDecoder.
  • The decode method of URLDecoder takes two arguments:
    • The first argument defines the URL to be decoded.
    • The second argument defines the decoding scheme to be used.
  • After decoding, the resulting decoded URL is returned.
  • We create two variables: prevURL, which is empty, and decodeURL, which contains the URL to be decoded.
  • We create an iteration that runs until prevURL!=decodeURL
  • Now we update prevURL to decodeURL and update decodeURL with the decoded value of the URL passed.
  • As you can see, prevURL!=decodeURL, so we run it again and again.
  • Now, prevURL=decodeURL, so the decoded URL is returned.

Sample Code

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

public class DecodeURLExample {
public static void main(String a[]){
try {
System.out.println(URLDecoder.decode("special+chars%3A+%26%25*+", "UTF-8"));
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
}
}
}

Output

special chars: &%* 

Categorized in:

Tagged in:

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,