Sunday 15 April 2012

Creating Tiny URLs in code

Calling api from

Anyway...  I needed to dynamically create short urls from the long urls which are so useful in my website but so cumbersome when dealing with things like twitter, so I looked round for an easy to integrate solution and choose predominantly because of its simple interface and long standing reputation.

TinyURL has a really simple api which  is called by passing a the long url as a query string to{0} (e.g. returns a link to a TinyURL in the format

I created a .net function which used the HttpWebRequest class to call the TinyURL api and then strip out the response.

public string getTinyURL(string longURL) { string shortUrl = ""; try {
// build TinyURL api URL string tinyURLApiUrl 
= "{0}"; tinyURLApiUrl 
= tinyURLApiUrl.Replace("{0}", longURL);  
 // call the URL and get the response HttpWebRequest request 
= (HttpWebRequest)WebRequest.Create(tinyURLApiUrl); WebResponse response = request.GetResponse();  // put the response into a stream Stream responseStream 
= request.GetResponse().GetResponseStream();  // read the short URL from the stream StreamReader reader 
= new StreamReader(responseStream); shortUrl = reader.ReadToEnd(); } catch (Exception e) { // something went wrong! } return shortUrl; }

So call this function passing in a Long URL and it returns a corresponding TinyURL.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.