buy cialis professional

Jun 7

Convert Short Url to Long Url with Java

Category: geek,java,twitter

Wikipedia :

Twitter is an online social networking service and microblogging service that enables its users to send and read text-based posts of up to 140 characters, known as “tweets”.

In microbloging service like Twitter , User must limit the text to 140 characters and URL can be some time very long. Some compagnies(Bitly, TinyURL,…) offer service to reduce your URL with a result like this http://bit.ly/lO2Pan.

In some situation, you have to transform short url to the original to analyse some tweets. For this, technically, you must follow the redirection to get this URL. My solution is to have a loop reading the content of the header and to be more specific the field location until the last URL.

The result :

  1. package com.nihed.tools;
  2.  
  3. import java.io.IOException;
  4. import java.net.HttpURLConnection;
  5. import java.net.MalformedURLException;
  6. import java.net.URL;
  7. import java.net.URLConnection;
  8.  
  9. /**
  10.  *
  11.  * @author Nihed MBAREK
  12.  */
  13. public class UrlTools {
  14.  
  15.     public static String getLongUrl(String shortUrl) throws MalformedURLException, IOException {
  16.         String result = shortUrl;
  17.         String header;
  18.             do {
  19.                 URL url = new URL(result);
  20.                 HttpURLConnection.setFollowRedirects(false);
  21.                 URLConnection conn = url.openConnection();
  22.                 header = conn.getHeaderField(null);
  23.                 String location = conn.getHeaderField("location");
  24.                 if (location != null) {
  25.                     result = location;
  26.                 }
  27.             } while (header.contains("301"));
  28.  
  29.         return result;
  30.     }
  31. }

Now, you can call this method in your class like this :

  1. String result = UrlTools.getLongUrl("http://bit.ly/lO2Pan");

ps: waiting for your questions :)


4 comments

4 Comments so far

  1. JavaPins June 8th, 2012 2:57 am

    Convert Short Url to Long Url with Java…

    Thank you for submitting this cool story – Trackback from JavaPins…

  2. franco graziosi June 10th, 2012 5:38 pm

    Smart solution! Thank you very much.

  3. Seigneur Canard March 8th, 2014 2:31 pm

    Hi,
    Thanks for this, work really great!
    I do have troubles with a few Url though I think it’s because the sites use PHP, nothing much but I was wondering if you had a patch for these cases :
    http://bit.ly/Pc1Z3v
    http://bit.ly/fL0jIx
    http://goo.gl/QUMKna
    http://bit.ly/1hRVT24
    http://goo.gl/YlBMSf

  4. nihed March 10th, 2014 1:27 pm

    Your cases represent a local redirection :)
    I never thinked to this cases.

Leave a comment