Bit.ly API: Shorten URLs / Reverse Long URLs / Get QR Code Image

17. March 2011 16:03

.NET Framework API C# Utils  0 Comments

If you have long URLs and other and want to create short URLs then Bit.ly API can help. I wrote a wrapper class which can let me create short URLs in jiffy. I was working on Bit.ly API to create my short URLs with a click of a button (that's for my personal use). Therefore, I ended up with a 'short' class to create shor URLs using Bit.ly API. What you need is a login and an apikey, which you can have one for yourself by signing up for a free account. You can find your apikey here after login. The class gives you two ways to make short URL, one with XML and the other with plain TEXT. I haven't write anything for JSON as it was not required at all to me in any ways. I am using plain TEXT for this example. You can read Bit.ly API official documentation for more information.

The below class can be used to create short URLs using Bit.ly API, reverse the short URLs and get the original URL. Also if you are not aware you can have a QR code of your short URL. Read more about QR Code here. If you are using Bit.ly or Goo.gl to shorten your URLs then you can have the QR code image by adding .qrcode in the end of the short URL (See in the code example below)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Net;
using System.IO;

namespace Bitly.API
{

    public class BitlyData
    {
        #region Properties

        public static string APIKEY { get; set; }
        public static string LoginName { get; set; }

        public static string StatusCode { get; set; }
        public static string StatusDesc { get; set; }
        public static string ShortURL { get; set; }
        public static string LongURL { get; set; }
        public static string HashCode { get; set; }
        public static string GlobalCode { get; set; }
        public static string NewHash { get; set; }

        #endregion
    }

    public class Bitly
    {

        #region Bit.Ly Variables

        private static string URL = "http://api.bit.ly/v3/shorten?login=";

        private static string BitResponse = "";

        #endregion

        #region Enums

        public enum Format
        {
            XML,
            JSON,
            TXT
        }

        #endregion

        #region Sample Response
        //        <?xml version="1.0" encoding="utf-8"?>
        //<response>
        //    <status_code>200</status_code>
        //    <status_txt>OK</status_txt>
        //    <data>
        //        <url>http://bit.ly/ekYLee</url>
        //        <hash>ekYLee</hash>
        //        <global_hash>gBH72m</global_hash>
        //        <long_url>http://midnightprogrammer.net/post/Windows-7-Development-Working-With-Task-Dialog-Class.aspx</long_url>
        //        <new_hash>1</new_hash>
        //    </data>
        //</response>

        #endregion

        public static string ShortURL(string LongURL, Format ReqFormat = Format.TXT)
        {
            string sURL = string.Empty;
            string BitLyURL = URL + BitlyData.LoginName + "&apikey=" + BitlyData.APIKEY + "&longUrl=" + LongURL + "&format=";

            if (ReqFormat == Format.JSON)
            {
                throw new NotImplementedException("This method is not implemented yet!");
            }

            if (ReqFormat == Format.XML)
            {
                BitResponse = new WebClient().DownloadString(BitLyURL + "xml");
                string Response = BitResponse;

                XmlDocument doc = new XmlDocument();
                doc.LoadXml(Response);
                XmlNodeList XlistResponse = doc.GetElementsByTagName("response");

                foreach (XmlNode XResnode in XlistResponse)
                {
                    XmlElement ResElm = (XmlElement)XResnode;

                    BitlyData.StatusCode = ResElm.GetElementsByTagName("status_code")[0].InnerText;

                    if (BitlyData.StatusCode != "200")
                    {
                        BitlyData.StatusDesc = ResElm.GetElementsByTagName("status_txt")[0].InnerText;
                        return BitlyData.StatusDesc;
                    }
                }

                if (BitlyData.StatusCode == "200")
                {

                    XmlNodeList XlistData = doc.GetElementsByTagName("data");

                    foreach (XmlNode XDatanode in XlistData)
                    {
                        XmlElement DataElm = (XmlElement)XDatanode;

                        BitlyData.ShortURL = DataElm.GetElementsByTagName("url")[0].InnerText;
                        BitlyData.LongURL = DataElm.GetElementsByTagName("long_url")[0].InnerText;
                        BitlyData.HashCode = DataElm.GetElementsByTagName("hash")[0].InnerText;
                        BitlyData.GlobalCode = DataElm.GetElementsByTagName("global_hash")[0].InnerText;
                        BitlyData.NewHash = DataElm.GetElementsByTagName("new_hash")[0].InnerText;
                    }
                }
            }

            if (ReqFormat == Format.TXT)
            {
                if (ReqFormat == Format.TXT)
                {
                    BitResponse = new WebClient().DownloadString(BitLyURL + "txt");
                    string Response = BitResponse;

                    BitlyData.ShortURL = Response;
                }
            }

            return sURL = BitlyData.ShortURL;
        }

        public static string ReverseShortURL(string ShortURL)
        {
            HttpWebRequest Webrequest = (HttpWebRequest)HttpWebRequest.Create(ShortURL);
            HttpWebResponse Webresponse = (HttpWebResponse)Webrequest.GetResponse();
            Uri uri = Webresponse.ResponseUri;
            return uri.AbsoluteUri;
        }

        public static string GetQRCodeURL(string ShortURL)
        {
            string QRCodeURL = string.Empty;
            QRCodeURL = ShortURL + ".qrcode";
            return QRCodeURL;
        }
    }
}

In the above class you can see that the second parameter is accepting TXT by default. So, if you call the method with or without the second parameter it will still work with the default parameter TXT. The enumeration called Format contains all the possible format of all the formats which is accepted by Bit.ly API. The second parameter in the class above should be removed if you plan to use the above code with the lower versions of .NET i.e. 3.x / 2.0

Sample Usage .NET 3.x / 2.0

Bitly.API.BitlyData.LoginName = "LOGIN NAME GOES HERE";
Bitly.API.BitlyData.APIKEY = "API KEY GOES HERE";
Console.WriteLine("Short URL: "+Bitly.API.Bitly.ShortURL("http://midnightprogrammer.net/post/9-Promises-Should-Be-Taken-Before-Choosing-IT-Profession.aspx", Bitly.API.Bitly.Format.TXT));
Console.WriteLine("Reverse URL: "+Bitly.API.Bitly.ReverseShortURL("http://bit.ly/eZ1kdb"));
Console.WriteLine("QRCode Image URL " + Bitly.API.Bitly.GetQRCodeURL("http://bit.ly/eZ1kdb"));

Sample usage .NET 4.0

Bitly.API.BitlyData.LoginName = "LOGIN NAME GOES HERE";
Bitly.API.BitlyData.APIKEY = "API KEY GOES HERE";
Console.WriteLine("Short URL: "+Bitly.API.Bitly.ShortURL("http://midnightprogrammer.net/post/9-Promises-Should-Be-Taken-Before-Choosing-IT-Profession.aspx", Bitly.API.Bitly.Format.TXT));
Console.WriteLine("Reverse URL: "+Bitly.API.Bitly.ReverseShortURL("http://bit.ly/eZ1kdb"));
Console.WriteLine("QRCode Image URL " + Bitly.API.Bitly.GetQRCodeURL("http://bit.ly/eZ1kdb"));

I have tested my code with Console Application, but you can test it with web or Windows form application. Note that the default parameters are only accepted if you are working with .NET 4.0 and not by the lower versions of .NET. If you wish to use the second parameter in .NET 4 then also it will work, but not using it with lower version will give you error.

I hope this class helps someone around the globe!

Currently rated 4.3 by 3 people

Comments (0)

Add Comment

Visit blogadda.com to discover Indian blogs Computers Blogs