Tools and Technologies used in this article :

  1. Eclipse Kepler 4.3.1

  2. JDK 1.6


1. How URL Shortener works?

  1. URL shortening service provider (say Google URL Shortener) generates an unique key (say WT6eFw) for the corresponding long url (say and associates it with the url to form the shortened url (say

  2. On accessing the shortened url (, Server returns HTTP Response having HTTP status code 301 (moved permanently), 302 (moved temporarily), or 307 (temporary redirect) along with the "Location" HTTP header containing the destination URL.

    Try Http Headers Viewer Web Tool as shown below
  3. On receiving the redirection indication, Browser redirects the user to the new "Location" found in the header.


2. How Our URL Expander will work?

  1. Make HttpURLConnection to the shortened url (say

  2. Extract the value of HTTP header field "Location". And this value is nothing but the expanded or actual destination URL.

  3. Close the connection.


3. Code



 * @author Abhijit Ghosh
 * @version 1.0
public class UrlExpander {

	public static void main(String[] args) throws IOException {
		String shortenedUrl = "";
		String expandedURL = expandUrl(shortenedUrl);
		System.out.println(shortenedUrl + "-->" + expandedURL); 
	public static String expandUrl(String shortenedUrl) throws IOException {
		URL url = new URL(shortenedUrl);	
		// open connection
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY); 
        // stop following browser redirect
        // extract location header containing the actual destination URL
        String expandedURL = httpURLConnection.getHeaderField("Location");
        return expandedURL;
Note : setInstanceFollowRedirects to false to avoid automatic redirection just like browser.
Console Output>


4. Live Demo

For live demo browse Url Expander Web Tool.


Download SrcCodes

tool-url-expander: GitHub or zip