Introduction
This article presents you a programmatic way to generate a short URL from a long URL. This is especially useful when you want to send e-mail messages (or even instant messages) to others and want to avoid the clients to break long URLs into multiple lines, thus rending them unclickable.
E.g. a long URL could be
http://www.de.map24.com/source/print/v3.0.1/
cnt_route_print_options.php?map24_sid=
d59b9f7b08f2de1e6b996cdc87972d41_MTAuMzkuOS40&map=1
And a short URL generated from this long URL could be
http://tinyurl.com/ynh3hb
To read a more detailed description, please see www.tinyurl.com.
The basics of services like TinyURL.com is that they keep a simple dictionary (also called "hash table" or "associative array") that stores the short URL as the key and the long URL as the value of an entry in the dictionary. When you enter the short URL into your web browser, a lookup is done and a redirect is executed to the long URL.
For instant testing the code of this article, visit www.zeta-sw.com/tinyurl.
What the web service does
The web service I've written is simply a wrapper to TinyURL.com. It has one simple method to call:
string MakeTinyUrl( string longUrl );
You pass a long URL and get a short URL. That's it.
Behind the scenes
The download as of now contains not one backend, but two:
1.) Interface to TinyURL.com
This was my first implementation. Since TinyURL.com does not offer a programatic way to access the service, I basically do a HTTP post to the TinyURL.com site and then screen-scrapping the results with some Regular Expressions.
That of course means that I must adjust the code whenever the TinyURL.com guys change their output HTML.
2.) Interface to SLink.in
Fortunately, this week, my co-worker Rainer Bendig registered the domain slink.in (Since you don't know Rainer, to sum up, he is the guy that constantly buys and sells domain names - in our office he is already infamous for registering more domains per day than he answers customer support calls :-).
At this domain, Rainer provides the same functionality than TinyURL.com but also accessible as a web service. I enhanced my application so that you are now able to switch to SLink.in by simply changing a configuration value in the Web.config file.
Effectively you can now use my web service to access another web service, but with a consistent interface. If I add more alternatives in the future, the web service that is presented to the consuming code still stays constant, because the calles to the different services happen in the backend.
Points of Interest
Special topics covered in the code include:
Enjoy the web service! And as always, please post your comments, questions, bug reports or worships in the comment section below. I really do appreciate your feedback!
History
- 2006-12-07: First version created.