Nowadays we use different URL shortening services (like, TinyURL, Google URL Shortener etc.) to shorten long URL to fit in micro-blogging sites (like Twitter), to beautify a link, view analytics on link clicks, make a link manageable for sharing (in SMS or printed hard copy, book, magazine etc.) or obscure the underlying address. But large portion of shortened links are used just to disguise spam or bad-sites containing malware, spyware, XSS attacks etc. So for safe browsing, sometimes revealing the destination of shortened link is necessary too.

Here, we'll discuss one programmatic approach (using to expand shortened links.

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 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

All code samples shown in this post are available on GitHub.