Home > Techniques > Using bit.ly URL Shortening From ASP.NET (REST/JSON)

Using bit.ly URL Shortening From ASP.NET (REST/JSON)


As part of my ‘learning ASP.NET’ series of posts, I thought I would discuss using the bit.ly url shortening API. I will add auto shortening to my SpiniTweet application. SpiniTweet simply takes the last song played on WMFO from Spinitron, and creates a nicely formatted tweetable string. You click, ‘Tweet This’, and then you don’t have to re-type your tracks as you are djing on air to let people know what you are playing. I like to include a link to listen to ‘MFO live via the web, in case someone wants to tune in. This is the link I want to shorten.

First off, apparently bit.ly doesn’t reuse links, so in my case I really don’t need to do this programmatically. But where is the fun in that?!?! Plus, I want to eventually add the ability for any link to be shortened in SpiniTweet, not just the WMFO listener link.

After you sign up for bit.ly, you get your API key in your profile. This is needed because they limit the total number of connects at one time. Next, check out the documentation wiki! bit.ly uses a REST api. If you really want details you can go read that linked wiki page. The bit.ly REST api is simple. We will be most interested in the ’shorten’ command, but there are others for doing things like expanding links and getting stats.

Our goal will be to send a url similar to this:

http://api.bit.ly/shorten?version=2.0.1&longUrl=http://cnn.com&login=bitlyapidemo&apiKey=R_0da49e0a9118ff35f52f629d2d71bf07

We can do that with a little chunk of code like so:

private String GetShortenedURL(String inURL)
{
	String shortURL = "";
	String queryURL = "http://api.bit.ly/shorten?version=2.0.1&longUrl=" + inURL + "&login=bitlyapidemo&apiKey=R_0da49e0a9118ff35f52f629d2d71bf07";

	HttpWebRequest request = WebRequest.Create(queryURL) as HttpWebRequest;

	using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
	{
		StreamReader reader = new StreamReader(response.GetResponseStream());
		String jsonResults = reader.ReadToEnd();
		int indexOfBefore = jsonResults.IndexOf("shortUrl\": \"") + 12;
		int indexOfAfter = jsonResults.IndexOf("\"", indexOfBefore);
		shortURL = jsonResults.Substring(indexOfBefore, indexOfAfter - indexOfBefore );
	}

	return shortURL;
}

Note that the results come back via JSON, but you can also request XML. While it may seem difficult at first, it actually is very simple. I thought initially that I needed to figure out how to parse the JSON output. I found that .NET 3.5 had support for a JSON serialization class. However, in this case, all we care about is the “shortUrl” output. And since it is returned as a string, why not just parse it out ourselves.

Done! Life really is Too Short.

  1. No comments yet.
  1. No trackbacks yet.