Popularity of services like twitter and other social networking sites have resulted in an exponential growth in the number of URL shortening services. bit.ly, tr.im are just few of the example. Though these URL shortening services solve a major issue of long URLs and save space where it is required, these services have a major downside to it.
Know where this link will lead you?
Yes, that is the major problem with these sites. URL like http://tr.im/abcd will not tell you where it takes you after you click on them. So, it is hard to find whether the short URL points where you expect it to be. In this post, I’ll show how to programmatically discover the hidden URL behind the shortened one.
How it works
When you are visiting a shortened URL, the server at the other end retrieves the real URL from its database using the short URL and redirects you to that URL. Yes, there might be some sites which don’t follow this process, they might show some info about the target URL and ask visitor to confirm that they want to visit that URL etc. However for those sites which use straight forward approach, we can easily find out the real URL by doing a HEAD request. In the response headers, we’ll look for location header. The value of the location header is what we want. For most of the popular services, this will be the original URL. Code follows.
Code in C#
HttpWebRequest req=WebRequest.Create(UrlToExpand) as HttpWebRequest ;
req.AllowAutoRedirect=false;
req.Method=”HEAD”;
HttpWebResponse res= req.GetResponse() as HttpWebResponse;
string url=res.GetResponseHeader(“location”);
if(string.IsNullOrEmpty(url))
Console.WriteLine(“no redirection. Might not be using this method or might not be a URL shortening service.”);
else
Console.WriteLine(“The expanded URL is ” + url);
Obviously you will have to change the code to meet your needs, handle Exceptions properly etc. This code works well with services like bit.ly, tr.im and tinyurl.com. I would be interested to know its success with other such services. Let in the comments and suggestions.