Link Shortener’s : Bit.ly & C# Part III
In the first entry looking at the Bit.ly API and with it we looked at hoe to shorten a link and parse the response in either JSON or XML. In the 2nd entry we looked at how to extend the shortened link, and we looked at the different formats Bitly send back, like JSON and XML.
In today’s entry we’ll delve deeper into their API and look at finding out how many times a link has been clicked and retrieve other information that is available in the API. Did you know that you can lookup a link by its shortened value, meaning you can find the original link, just something to think about. These are the things we will be looking at in this final entry on the Bit.ly API.
NOTE: Dont worry, if you’ve enjoyed the first three then let me know, there are many more out there I can write about.
So let’s have some fun now, the first think we look at it getting the number of times a link was clicked. With this we get ‘clicks’ and ‘global clicks’, let’s explain the difference in the two. Clicks is how many times toe current user has clicked and Global Clicks is how many times it’s clicked by everyone.
Now that we have that out-of-the-way let’s move on to some code and how to use it.
GetClicks
/// <summary>
/// method for finding out many times has been clicked
/// </summary>
/// <param name="url">the IURL we're checking</param>
/// <param name="login">out Bit.ly login</param>
/// <param name="key">our Bit.ly API key</param>
/// <param name="globalClicks">out parameter, used to get the global clicks</param>
/// <returns></returns>
public int GetClicks(string url, string login, string key, out int globalClicks)
{
//use EscapeUriString to sanitize the link
url = Uri.EscapeUriString(url);
//each function of Bit.ly has its own URL, here we're building the urk to retrieve clicks
string reqUri = String.Format(clicksUrl + @"{0}&apiKey={1}&shortUrl={2}&format=xml",login, key, url);
//create a web request, sett it's timeout to 10 seconds
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(reqUri);
request.Timeout = 10000; // 10 seconds
//get the response stream from our request
Stream stream = request.GetResponse().GetResponseStream();
//now we opent that stream with XmlDocument.Load
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(stream);
//simple error checking on ghe returned XML
if (xmlDoc["response"]["status_code"].InnerText != "200")
throw new WebException(xmlDoc["response"]["status_txt"].InnerText);
XmlElement el = xmlDoc["response"]["data"]["clicks"];
//get the global clicks
globalClicks = int.Parse(el["global_clicks"].InnerText);
//return the data for user_clicks
return int.Parse(el["user_clicks"].InnerText);
}
Let’s create a short usl and try this function on it, keep mind min that clicks & global clicks will be 0 because no one has clicked on it. Before we can do anything we need an instance of our bitly class (I’m using a simple console application fr testing) and here is how I initialize the service:
Bitly service = new Bitly
{
BitlyLogin = "bitlyapidemo",
BitlyAPIKey = "R_0da49e0a9118ff35f52f629d2d71bf07",
UrlToShorten = "http://blog.psychocoder.net/index.php/2011/04/06/link-shorteners-bit-ly-c-part-i/"
};
Now we have our login name, our API key and a url to shorten (I picked one from my blog). Here’s the code for shortening the provided url
var ShrunkUrl = service.ShortenUrl(service.UrlToShorten, service.BitlyLogin, service.BitlyAPIKey, Bitly.ResponseFormat.XML);
string url = ParseXmlResponse(ShrunkUrl, false);
Console.WriteLine(url);
/csharp]
First you will notice we want out data back in ML format, second a call to a method So we looked at this method back in the first entry bt let's show it for a refresher:
<strong>ParseXmlResponse</strong>:
1
/// <summary>
/// a method for parsing the XML returned from a Bit.ly call
/// </summary>
/// <param name="xml"></param>
/// <param name="expand"></param>
/// <returns></returns>
private static string ParseXmlResponse(string xml, bool expand)
{
//create an XML document
XmlDocument xmlDoc = new XmlDocument();
//load the XML string
xmlDoc.LoadXml(xml);
string url = string.Empty;
//populate an XmlNodeList with SelectNodes of the XmlDocument
XmlNodeList nodeList = (expand) ? nodeList = xmlDoc.SelectNodes("/response/data/entry") : nodeList = xmlDoc.SelectNodes("/response/data/entry");
//now find the shortened url (or extended is expand is set to true
foreach (XmlNode node in nodeList)
url = (expand) ? node["long_url"].InnerText : node["url"].InnerText;
return url;
}
And if you look at the screen caps I posted you will see the shortened URL along with user_clicks and global_clicks. Now we move on to getting information for the shortened url. With this method you can find out who made link and the title of the page.
GetInfo:
/// <summary>
/// method for getting information from a shortened link
/// </summary>
/// <param name="url">the user we're checking</param>
/// <param name="login">out Bit.ly login</param>
/// <param name="key">our Bit.ly key</param>
/// <param name="createdBy">our parameter holding who created the sshortened link</param>
/// <returns></returns>
public string GetInfo(string url, string login, string key, out string createdBy)
{
//use EscapeUriString to sanitize the link
url = Uri.EscapeUriString(url);
//build out 'look for info' URL
string reqUri = String.Format(infoUrl + @"{0}&apiKey={1}&shortUrl={2}&format=xml" ,login, key, url);
//create a web request, sett it's timeout to 10 seconds
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(reqUri);
request.Timeout = 10000; // 10 seconds
//get the response stream from our request
Stream stream = request.GetResponse().GetResponseStream();
//now we opent that stream with XmlDocument.Load
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(stream);
//simple error checking on ghe returned XML
if (xmlDoc["response"]["status_code"].InnerText != "200")
throw new WebException(xmlDoc["response"]["status_txt"].InnerText);
XmlElement el = xmlDoc["response"]["data"]["info"];
//get the creators name
createdBy = el["created_by"].InnerText;
//get the title
return el["title"].InnerText;
Console.ReadLine();
}
In our console application we shrink a URL then get’s it’s information link eo:
Bitly service = new Bitly
{
BitlyLogin = "bitlyapidemo",
BitlyAPIKey = "R_0da49e0a9118ff35f52f629d2d71bf07",
UrlToShorten = "http://blog.psychocoder.net/index.php/2011/04/06/link-shorteners-bit-ly-c-part-i/"
};
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);
string createdBy = string.Empty;
var y = service.GetInfo(ParseXmlResponse(ShrunkUrl, false), service.BitlyLogin, service.BitlyAPIKey, out createdBy);
Console.WriteLine(y);
Console.WriteLine(createdBy);
Console.ReadLine();
You’ll easily see it’s the actual results, the page title, who created it, the 2 pieces of information we were seeking. The last think we’ll be looking at in this entry is the ability to look up a long URL and se if it’s been shortened before. So here is the code for said actions:
LookupLink:
/// <summary>
/// method to check ig a long URL has ever been shortened
/// if it has then return the short URL
/// </summary>
/// <param name="url">the long URL we're testing</param>
/// <param name="login">our Bit.ly login</param>
/// <param name="key">out Bit.ly key</param>
/// <returns></returns>
public string LookupLink(string url,string login,string key)
{
//use EscapeUriString to sanitize the link
url = Uri.EscapeUriString(url);
//each function of Bit.ly has its own URL, here we're building the one to see if a link has been shortened before
string reqUrl = string.Format(lookupUrl + @"{0}&apiKey={1}&url={2}&format=xml", login, key, url);
//create a web request, sett it's timeout to 10 seconds
HttpWebRequest request=(HttpWebRequest)WebRequest.Create(reqUrl);
request.Timeout=10000; //10 seconds
//get the response stream from our request
Stream stream = request.GetResponse().GetResponseStream();
//now we opent that stream with XmlDocument.Load
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(stream);
//simple error checking on ghe returned XML
if (xmlDoc["response"]["status_code"].InnerText != "200")
throw new WebException(xmlDoc["response"]["status_txt"].InnerText);
if(xmlDoc["response"]["data"]["lookup"]["error"] == null)
return null; //nothing found so return null
//if it's been determined that the link has been shortened the we return that url
return xmlDoc["response"]["data"]["lookup"]["short_url"].InnerText;
}
And you can call tis method like this(remember that I’m using simple console application). After I initialize my Bitly class. I will then use the default link for checking. First initialize the Bitly class
Bitly service = new Bitly
{
BitlyLogin = "bitlyapidemo",
BitlyAPIKey = "R_0da49e0a9118ff35f52f629d2d71bf07c",
UrlToShorten = "http://blog.psychocoder.net/index.php/2011/04/06/link-shorteners-bit-ly-c-part-i/"
};
Now we have that information it’s time to look up that use to see if it’s been shrunk before:
string link = service.LookupLink(service.UrlToShorten, service.BitlyLogin, service.BitlyAPIKey); Console.WriteLine(link); Console.ReadLine();
I think that’s enough information for Part III, but trust me we will have it settled in part IV, in that edition there is a lot to cover so it may be longer than the previous entries.
Thanks for reading, hope you found this informative, I know I have.


Comments