buy cialis professional

Archive for June, 2012

Convert Short Url to Long Url with Java

June 07th, 2012 | 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