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 http://www.srccodes.com/tools/misc/url-expander) and associates it with the url to form the shortened url (say http://goo.gl/WT6eFw).

  2. On accessing the shortened url (http://goo.gl/WT6eFw), 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
    http-headers-viewer
  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 http://goo.gl/WT6eFw).

  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

File: UrlExpander.java
package com.srccodes.tools.misc;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;

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

	public static void main(String[] args) throws IOException {
		String shortenedUrl = "http://goo.gl/WT6eFw";
		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
        httpURLConnection.setInstanceFollowRedirects(false);
        
        // extract location header containing the actual destination URL
        String expandedURL = httpURLConnection.getHeaderField("Location");
        httpURLConnection.disconnect();
        
        return expandedURL;
	}
}
Note : setInstanceFollowRedirects to false to avoid automatic redirection just like browser.
Console Output
http://goo.gl/WT6eFw-->http://www.srccodes.com/tools/misc/url-expander

 

4. Live Demo

For live demo browse Url Expander Web Tool.

 

Download SrcCodes

tool-url-expander: GitHub or zip

 

References