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
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
[pastacode lang=”java” manual=”import%20java.io.UnsupportedEncodingException%3B%0Aimport%20java.net.URLDecoder%3B%0A%20%0Apublic%20class%20DecodeURLExample%20%7B%0A%20%20%20%20public%20static%20void%20main(String%20a%5B%5D)%7B%0A%20%20%20%20%20%20%20%20try%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20System.out.println(URLDecoder.decode(%22special%2Bchars%253A%2B%2526%2525*%2B%22%2C%20%22UTF-8%22))%3B%0A%20%20%20%20%20%20%20%20%7D%20catch%20(UnsupportedEncodingException%20ex)%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20ex.printStackTrace()%3B%0A%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%7D%0A%7D” message=”” highlight=”” provider=”manual”/]Output
special chars: &%*
