Link Shortener’s : Bit.ly & C# Part II
Yesterday we started on an adventure which is the Bit.ly API. It’s quite a nice API, there is so much you can do with this API its list of features are quite outstanding. I showed how you can shrink a URL/Link and how to parse the format that’s returned (Json, XML or Text), so today we’re going to look at how to restore a URL/Link.
To make things easier we’ll use the class file we created yesterday (no need reinventing the wheel right). Since we already have methods to parse XML and Json I feel it wouldn’t be very productive to create them again. As stated before there are three ways to get your information, Json (default returned data), XML and Text. So let’s take a look at how Bit.ly returns the data to you.
And here is an example of the data being returned in Json format:
{
"status_code": 200,
"status_txt": "OK",
"data":
{
"long_url": "http:\/\/blog.psychocoder.net\/index.php\/2011\/04\/06\/link-shorteners-bit-ly-c-part-i\/",
"url: "http:\/\/rlm.cc\/eLr5f8",
"hash": "eLr5f8",
"global_hash": "ekRj8e",
"new_hash": 0
}
}
And this is how it will look if you chose SML as your return type:
<?xml version="1.0" encoding="utf-8"?>
<response>
<status_code>200</status_code>
<status_txt>OK</status_txt>
<data>
<url>http://rlm.cc/eLr5f8</url>
<hash>eLr5f8</hash>
<global_hash>ekRj8e</global_hash>
<long_url>http://blog.psychocoder.net/index.php/2011/04/06/link-shortene
rs-bit-ly-c-part-i/</long_url>
<new_hash>0</new_hash>
</data>
</response>
For today’s entry we will be working with the XML format, don’t worry this is like a 4 part series on Bitly and soon we will work with nothing but Json.
So let’s get this thing on the road and make our first expanded URL. Keep in mind that this is a tad more complicated than one would think. So we’ll start working with the Json format first. So now we create an instance of our Bitly class along with members initialized. Here’s our newly created Service class:
Bitly service = new Bitly();
{
service.BitlyLogin = "psychocoder";
service.BitlyAPIKey = "R_28abcf9aa726f1ddc020734675631d8c";
service.UrlToShorten = "http://blog.psychocoder.net/index.php/2011/04/06/link-shorteners-bit-ly-c-part-i/";
};
1
so we initialized our Bitly class and set the properties all in one fail swoop (much nicer that way if you ask me). Now we move on and actually shorten a URL so we have something to extend. This code is merely a sample of what can be done with the Bit.ly API. Heres the code we use to send to the host.
1
Console.WriteLine("Shortened URL");
var ShrunkUrl = service.ShortenUrl(service.UrlToShorten, service.BitlyLogin, service.BitlyAPIKey, Bitly.ResponseFormat.XML);
string url = ParseXmlResponse(ShrunkUrl, false);
Console.WriteLine(url);
So here’s how this works, we call the above code so we can get an expanded (original) URL. We have just shortened a URL which we’re going to want to restore. Doing it Json here’s the results from the practice link we shortened: So now we have a couple of options, for the sake of this write-up
{
"status_code": 200,
"status_txt": "OK",
"data":
{
"long_url": "http:\/\/blog.psychocoder.net\/index.php\/2011\/04\/06\/link-shorteners-bit-ly-c-part-i\/",
"url": "http:\/\/rlm.cc\/eLr5f8",
"hash": "eLr5f8",
global_hash": "ekRj8e",
"new_hash": 0
}
}
So now we have a couple of options, for the sake of this write-up I’m going to stick to XML. What needs to happen now is we need to value from the toolbox named hash. in the Bitly there are a couple overloaded methods for restoring a URL, the one we’ll be using will allow us to restore multiple shortened URL’s. This is the one we’re going to be using today:
public string ExpandUrl(string[] urlList, string login, string key, ResponseFormat f = ResponseFormat.XML)
{
string output;
string expandedUrl = string.Format(restoreUrl + @"{0}&apiKey={1}&format={2}",
login, key,format.ToString().ToLower());
if (urlList!= null)
{
foreach (string url in urlList)
expandedUrl += "&shortUrl=" + HttpUtility.UrlEncode(url);
}
return getFinalValue(expandedUrl, out output);
}
The code shown above is for creating a shortened URL calls a method in out Bitly class file telling it to shorten the provided URL, and this is how it looks
/// <summary>
/// method for shortening a URL utilizing the Bitly API
/// </summary>
/// <param name="longURL">URL to shorten</param>
/// <param name="login">Login for our account</param>
/// <param name="key">our Bitly API Key</param>
/// <param name="format">Thef format we wish to have returned to us</param>
/// <returns></returns>
public string ShortenUrl(string longURL, string login, string key, ResponseFormat format = ResponseFormat.XML)
{
//this will hold the shortened URL
string output;
//build the full URL for shortening the URL
string url = string.Format(shortenUrl + @"{0}&apiKey={1}&longUrl={2}&format={3}",
login, key, HttpUtility.UrlEncode(longURL), format.ToString().ToLower());
//get the finaly shortened URL (this is an external method that you will see later
return getFinalValue(url, out output);
}
Once we have the URL shortened we can pass that along to our method for restoring the shortened urls back to their original state. The code that handles this is
Console.WriteLine("Expanded URL");
string[] urls = new string[] { ShrunkUrl };
var expanded = service.ExpandUrl(urls, null,service.BitlyLogin, service.BitlyAPIKey, Bitly.ResponseFormat.XML);
var shortenedUrl = ParseXmlResponse(expanded, true);
Console.WriteLine(shortenedUrl);
Pretty simple once you get used to using.Well this is the end of Part II on the Bitly. In the next couple days I’ll be writing another one showing more of what this API i capable of. Thanks for reading.
NOTE: The methods you’ve seen from Bitly.cs all call a method named getFinalValue, if you’re going to be this specific code to learn this URL I owe it to you to give you that method, and here it is:
private static string getFinalValue(string URL, out string output)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(URL);
using (WebResponse webResponse = webRequest.GetResponse())
{
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
{
output = reader.ReadToEnd();
}
}
return output;
}
I started to notice a pattern, every method I wrote ended this way so why not write it once and use it multiple times.
Once again, thanks for reading and I hope you found it useful and informative. See you in the next episode.


Comments