Decode URL in Java

In Java, there is a predefined class for decoding as well as for encoding any URL. For decoding URL, ‘URLDecoder’ class is present and for encoding URL, ‘URLEncoder’ class is there.

Now in this tutorial, we will look at the Java decoder class.

In URLDecoder class there is a method called decode(),
which accepts two arguments –

  1. String URL which we want to decode.
  2. Specific encoding scheme in String format.

Algorithm:

  1. In the main method, declare a string URL that is encoded.
  2. Define a method that will decode the encoded URL.
  3. Pass the arguments accordingly.
  4. Print the output.

Now, we will look at our code:

public static void main(String[] args) {
        String url="https%3A%2F%2Fwww.codespeedy.com";  
        System.out.println("Decoded: "+decode(url));
}

In the above code, we have declared a string URL that is encoded and we want to decode it. In the second line of the main method, we are printing the output of the URL by passing it to the decode() method which will decode the URL.

Now we will look at our decode() method that is defined in the same class.

public static String decode(String url) {
                // using try and catch blocks for catching an errors 
    try {
      String decodedUrlString = URLDecoder.decode(url, "UTF-8");
      return decodedUrlString;
    } catch (Exception e) {
      // TODO: handle exception
      return "Issue while decoding"+e.getMessage();
    }
  }

URLDecoder is a predefined class in Java and which has a decoding method to decode an encoded URL. We are using a try-catch block for catching exceptions. The first argument in the decode method is our URL which has to be decoded and in the second argument, we have passed a specific encoding scheme. By storing the output of decoded URL we are returning that string.

Code:

package com.first;

import java.net.URLDecoder;

public class DecodeUrl {

  public static void main(String[] args) {
        String url="https%3A%2F%2Fwww.codespeedy.com";  
        System.out.println("Decoded: "+decode(url));
  }
  public static String decode(String url) {
    try {
      String decodedUrlString = URLDecoder.decode(url, "UTF-8");
      return decodedUrlString;
    } catch (Exception e) {
      // TODO: handle exception
      return "Issue while decoding"+e.getMessage();
    }
  }

}

That’s all for this tutorial.

Thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *