Open In App

Java.net.URLDecoder class in Java

Improve
Improve
Like Article
Like
Save
Share
Report

This is a utility class for HTML form decoding. It just performs the reverse of what URLEncoder class do, i.e. given an encoded string, it decodes it using the scheme specified. Generally when accessing the contents of request using getParameter() method in servlet programming, the values are automatically decoded before they are returned. But sometimes there may be a need to explicitly decode an otherwise URL encoded string.
The following steps are followed while decoding the strings:

  1. Alphanumeric characters and certain special characters such as ‘*‘, ‘_‘, ‘‘ and ‘.‘ remains unchanged.
  2. +‘ signs are converted into spaces.
  3. All other characters are decoded using the encoding scheme specified. The string of the form %xy, is converted to the character whose encoding would have resulted in this three character representation. W3C recommends using “UTF-8” for encoding purposes.

For example, the encoded string

u%40geeks+for+geeks

will be converted into the string representation where %40 will be replaced by an @ symbol and + signs are converted into space characters.

u@geeks for geeks

Methods :

    decode() : This is one and only method provided by this class. It as the name suggests returns an decoded string for the specified string. One method, which is now deprecated has only one parameter, the string to be decoded. It doesn’t let you specify the encoding scheme used and uses the platform default encoding scheme. Another version allows the specification of the encoding to be used, and thus is widely used.

    Syntax :public static String decode(String s)- @Deprecated
    Parameters :
    s : encoded string to be decoded
    
    Syntax :public static String decode(String s,
                String enc)
                         throws UnsupportedEncodingException
    Parameters : 
    s : string to be decoded
    enc : encoding to be used
    Throws :
    UnsupportedEncodingException : If the specified encoding is not used
    

Java Implementation :




// Java program to show decode() method of 
// URLDecoder class
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
  
public class urlDecoder 
{
    public static void main(String[] args) 
                             throws UnsupportedEncodingException 
    {
        // encoded string
        String encodedString = "u%40geeks+for+geeks";
        System.out.println("Encoded String :");
        System.out.println(encodedString);
          
        // decode() method
        System.out.println("Decoded String :");
        System.out.println(URLDecoder.decode(encodedString, "UTF-8"));
    }
}


Output :

Encoded String :
u%40geeks+for+geeks
Decoded String :
u@geeks for geeks

References :
Official Java Documentation


Last Updated : 16 Jun, 2017
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads