1

Which library or built in functionality would allow you to take a shorted URL like bitly, fb.me, google's shortener, etc... and get its final link in the fastest time?

thanks

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
James
  • 15,085
  • 25
  • 83
  • 120

3 Answers3

8

programming time mostly, I'm using httpclient from apache right now wondering if their are any alternatives built in

There's java.net.URLConnection.

String location = "http://tinyurl.com/so-hints";
HttpURLConnection connection = (HttpURLConnection) new URL(location).openConnection();
connection.setInstanceFollowRedirects(false);
while (connection.getResponseCode() / 100 == 3) {
    location = connection.getHeaderField("location");
    connection = (HttpURLConnection) new URL(location).openConnection();
}
System.out.println(location); // http://msmvps.com/blogs/jon_skeet/archive/2010/08/29/writing-the-perfect-question.aspx
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
2

This isn't a real answer, but you basically need to call the shortened URL via an HTTP Client, and then see what the 302 header in the response is. Then redirect the user to that URL.

(I wonder why you'd want to do this though, just send the shortened URL as a 302 redirect, and let them bounce again).

mlathe
  • 2,375
  • 1
  • 23
  • 42
  • I'm actually looking for a library or code that will do the following. I'm currently using httpclient to do it but I was looking for an alternative if there is something better like cURL I should be using. – James Dec 22 '10 at 01:58
  • Yea.. I would doubt that there is a direct way, since just letting the client deal with a 302 would be the obvious solution. Good luck though. – mlathe Dec 22 '10 at 02:02
2

I was looking for the same and what BalusC suggested above helped. I have a fix here that acts as an enhancement actually.

String location = "http://j.mp/mAag6Q";
HttpURLConnection connection = (HttpURLConnection) new URL(location).openConnection();
connection.setInstanceFollowRedirects(false);
while (connection.getResponseCode() / 100 == 3) {
    location = connection.getHeaderField("location");
    System.out.println(location);
    connection = (HttpURLConnection) new URL(location).openConnection();
    **connection.setInstanceFollowRedirects(false);**
}

Basically all I did was to set the connection's setInstanceFollowRedirects to false again in a loop so it handles multiple level redirection as well.

chirag
  • 345
  • 2
  • 7