If you’re active in social networks especially twitter and newsgroups, you might have seen lot of short URLs which encapsulates and redirect to actual long and cumbersome URLs. There are many websites which provides URL Redirection services like tinyurl.com , bit.ly and is.gd etc. Yeap, in programmer’s word, I will take courage to compare TinyURs as C/C++ macros as a simple single name replaces a bunch of statements.
Consider, twitter, each “tweet” is limited to 140 characters (length of single SMS) and if the user enables device updates, then he/she can read the updates through phone. Often the link you supposed to share either too length or takes more letters which can be used for your message.
http://sarathc.wordpress.com/2007/01/31/how-to-trim-leading-or-trailing-spaces-of-string-in-c/
The above URL is a link to my most active blog post. If this got converted using tinyurl.com, it may appear as http://tinyurl.com/bg487k
So you saved lot of spaces by putting this short url. Now let’s see how to write a simple C# function to shorten url. Each provides having different kind formats to specify actual URL and get the converted URL back. Most of the sites will be listed this as their API. Here I listed 3 of the most famous provider’s format.
| Is.gd | http://is.gd/api.php?longurl={your_url} |
| Bit.ly | http://bit.ly/api?url={your_url} |
| Tinyurl | http://tinyurl.com/api-create.php?url={your_url} |
.NET framework provides HttpWebRequest class to connect to make a web request to the desired website. So our responsibility is to send a formatted URL to desired website.
See the code below for coversion. I’ve done only primary error handling and supposed to deal with http:// and https:// urls
[sourcecode language='csharp']
using System;
using System.IO;
using System.Net;
using System.Text;
namespace ShortURL
{
enum ShortURLProvider
{
Bitly,
Isgd,
Tinyurl,
}
class ConvertURL
{
public static string ShortenURL(string strUrl, ShortURLProvider eService)
{
// return empty strings if not valid
if( !IsValidURL( strUrl ))
{
return “”;
}
string requestUrl = string.Format(GetRequestTemplate(eService), strUrl);
WebRequest request = HttpWebRequest.Create(requestUrl);
request.Proxy = null;
string strResult = null;
try
{
using (Stream responseStream = request.GetResponse().GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.ASCII);
strResult = reader.ReadToEnd();
if( !IsValidURL(strResult))
{
WebException w = new WebException(strResult);
throw w;
}
}
}
catch( Exception )
{
return strUrl; // eat it and return original url
}
// if converted is longer than original, return original
if ( strResult.Length > strUrl.Length)
strResult = strUrl;
return strResult;
}
/* Validate URL */
public static bool IsValidURL(string strurl)
{
// Validate the URL
if (true == strurl.ToLower().StartsWith(“http://”) || true == strurl.StartsWith(“https://”))
{
return true;
}
return false;
}
/* Request template for URL */
private static string GetRequestTemplate(ShortURLProvider eService)
{
string strRequest = null;
switch (eService)
{
case ShortURLProvider.Isgd:
strRequest = “http://is.gd/api.php?longurl={0}”;
break;
case ShortURLProvider.Bitly:
strRequest = “http://bit.ly/api?url={0}”; ;
break;
case ShortURLProvider.Tinyurl:
strRequest = “http://tinyurl.com/api-create.php?url={0}”;
break;
default:
break;
}
return strRequest;
}
}
}
[/sourcecode]
Here’s how client use the class.
[sourcecode language='csharp']
string strShortURL = ConvertURL.ShortenURL(textBoxOrgURL.Text, eProvider);
[/sourcecode]