Friday, July 10, 2009

Java: URL Encoder/Decoder

/* Simple java program for Encoding and Decoding URL
Below is complete tested code, directly you can run this program
*/

//SimpleURLEncoder.java

import java.net.*;

public class SimpleURLEncoder
{
public static void main(String[] args) throws Exception
{
String userUrl = "http://10.10.3.24/Product.jsp?username=scott&password=tiget";
URL url = url = new URL(userUrl);
String encodedUrl = encodedUrl = URLEncoder.encode(url.toString(),"UTF-8");
String decodedUrl = decodedUrl = URLDecoder.decode(encodedUrl,"UTF-8");

System.out.println("userUrl : "+userUrl);

System.out.println("encodedUrl : "+encodedUrl);
System.out.println("decodedUrl : "+decodedUrl);

}
}


/***************OUTPUT*****************/


userUrl : http://10.10.3.24/Product.jsp?username=scott&password=tiget
encodedUrl : http%3A%2F%2F10.10.3.24%2FProduct.jsp%3Fusername%3Dscott%26password
%3Dtiget
decodedUrl : http://10.10.3.24/Product.jsp?username=scott&password=tiget




//Same above example in detail


import java.net.*;//for URL
import java.io.*;//for UnsupportedEncodingException

public class SimpleURLEncoder
{
public static void main(String[] args)
{
String userUrl = "http://10.10.3.24/Product.jsp?username=scott&password=tiget";
URL url = null;
String encodedUrl = "";
String decodedUrl = "";

try
{
//Creates a URL object from the String representation.
url = new URL(userUrl);
}
catch (MalformedURLException ex)
{
//If the string specifies an unknown protocol.
System.out.println("MalformedURLException : "+ex);
}

try
{
encodedUrl = URLEncoder.encode(url.toString(),"UTF-8");
//UTF-8 : The name of a supported character encoding.
//The World Wide Web Consortium Recommendation states that UTF-8 should be used. Not doing so may introduce incompatibilites.
}
catch (UnsupportedEncodingException ex)
{
//If the named encoding is not supported
System.out.println("UnsupportedEncodingException : "+ex);
}

try
{
decodedUrl = URLDecoder.decode(encodedUrl,"UTF-8");
}
catch (UnsupportedEncodingException ex)
{
//If the named encoding is not supported
System.out.println("UnsupportedEncodingException : "+ex);
}

System.out.println("userUrl : "+userUrl);

System.out.println("encodedUrl : "+encodedUrl);
System.out.println("decodedUrl : "+decodedUrl);

}
}