A .NET Bit.ly API Helper Class (Visual Basic.NET)


I decided to write a helper class for using the Bit.ly API for creating short urls.  You know, those tiny links that you see all over Facebook, Twitter, etc.  The snippet below shows how you would use the helper class.  Not only can you shorten an url, you can shorted multiple urls in a single call as well as get stats and info about a bit.ly url.  If you are looking to incorporate bit.ly short urls in your application using their API access, this will save you some time.  The class uses the XmlSerializer for reading bit.ly’s response.

        ' Pass username and API key to instantiate
        Dim newbitlyAPI As New DataBatrix.bitlyAPI.bitlyAPI("bitlyapidemo", "R_0da49e0a9118ff35f52f629d2d71bf07")

        ' Sample of creating 1 short URL
        Dim shortenResponse As DataBatrix.bitlyAPI.bitlyShortenResponse = newbitlyAPI.Shorten("http://www.databatrix.com")
        Dim shortURL As String = ""
        If shortenResponse.results.Count > 0 Then
            shortURL = shortenResponse.results(0).shortUrl
        End If

        ' Sample of creating multiple short URLs
        Dim longUrls() As String = {"http://www.databatrix.com", "http://www.google.com"}
        Dim shortenResponses As DataBatrix.bitlyAPI.bitlyShortenResponse = newbitlyAPI.Shorten(longUrls)
        Dim shortURLs(1) As String
        For i As Integer = 0 To shortenResponses.results.Count - 1
            shortURLs(i) = shortenResponses.results(i).shortUrl

        Next

        ' Sample of getting bit.ly info...
        Dim info As DataBatrix.bitlyAPI.bitlyInfoResponse = newbitlyAPI.Info("2bYgqR")

        ' Sample of getting bit.ly stats...
        Dim stats As DataBatrix.bitlyAPI.bitlyStatsResponse = newbitlyAPI.Stats("http://bit.ly/1RmnUT")

Below is the helper class that I created.  You can download the VB file bitlyAPI.vb or a sample project TestBitly Project Files.

Imports System.Web
Imports System.Xml
Imports System.Xml.Serialization

Namespace DataBatrix.bitlyAPI
    Public Class bitlyAPI
        Const BaseAPIUrl As String = "http://api.bit.ly/"
        Const version As String = "2.0.1"
        Const format As String = "xml"

        Public login As String = String.Empty
        Public apiKey As String = String.Empty

        Sub New(ByVal login As String, ByVal apiKey As String)
            Me.login = login
            Me.apiKey = apiKey

        End Sub

        Private Function BuildBaseRequestURL(ByVal applicationName As String) As System.Text.StringBuilder
            Dim RequestUrl As New System.Text.StringBuilder()
            With RequestUrl
                .Append(BaseAPIUrl & HttpUtility.UrlEncode(applicationName) & "?")
                .Append("version=" & HttpUtility.UrlEncode(version) & "&")
                .Append("format=" & HttpUtility.UrlEncode(format) & "&")
                .Append("login=" & HttpUtility.UrlEncode(login) & "&")
                .Append("apiKey=" & HttpUtility.UrlEncode(apiKey) & "&")
            End With
            Return RequestUrl
        End Function

        Public Function Shorten(ByVal longUrl As String) As bitlyShortenResponse
            Dim logUrls() As String = {longUrl}
            Return Shorten(logUrls)
        End Function

        Public Function Shorten(ByVal longUrl() As String) As bitlyShortenResponse
            Dim RequestUrl As System.Text.StringBuilder = BuildBaseRequestURL("shorten")
            For Each s As String In longUrl
                RequestUrl.Append("&longUrl=" & HttpUtility.UrlEncode(s))

            Next
            Dim responseObj As DataBatrix.bitlyAPI.bitlyShortenResponse = Nothing
            Try
                Dim serializer = New XmlSerializer(GetType(DataBatrix.bitlyAPI.bitlyShortenResponse))
                Using reader As XmlTextReader = New XmlTextReader(RequestUrl.ToString())
                    responseObj = CType(serializer.Deserialize(reader), DataBatrix.bitlyAPI.bitlyShortenResponse)
                End Using

            Catch ex As Exception

            End Try

            If responseObj.errorCode > 0 Then
                Throw New ApplicationException("Error from bit.ly: " & responseObj.errorMessage)
            End If
            Return responseObj
        End Function
        Public Function Info(ByVal hash As String) As bitlyInfoResponse
            Dim RequestUrl As System.Text.StringBuilder = BuildBaseRequestURL("info")
            With RequestUrl
                .Append("hash=" & HttpUtility.UrlEncode(hash))
            End With

            Dim responseObj As DataBatrix.bitlyAPI.bitlyInfoResponse = Nothing
            Try
                Dim serializer = New XmlSerializer(GetType(DataBatrix.bitlyAPI.bitlyInfoResponse))
                Using reader As XmlTextReader = New XmlTextReader(RequestUrl.ToString())
                    responseObj = CType(serializer.Deserialize(reader), DataBatrix.bitlyAPI.bitlyInfoResponse)
                End Using

            Catch ex As Exception
                Throw New ApplicationException("API Error: " & ex.Message)
            End Try
            If responseObj.errorCode > 0 Then
                Throw New ApplicationException("Error from bit.ly: " & responseObj.errorMessage)
            End If
            Return responseObj
        End Function

        Public Function Stats(ByVal shortUrl As String) As bitlyStatsResponse
            Dim RequestUrl As System.Text.StringBuilder = BuildBaseRequestURL("stats")
            With RequestUrl
                .Append("shortUrl=" & HttpUtility.UrlEncode(shortUrl))

            End With

            Dim responseObj As DataBatrix.bitlyAPI.bitlyStatsResponse = Nothing
            Try
                Dim serializer = New XmlSerializer(GetType(DataBatrix.bitlyAPI.bitlyStatsResponse))
                Using reader As XmlTextReader = New XmlTextReader(RequestUrl.ToString())
                    responseObj = CType(serializer.Deserialize(reader), DataBatrix.bitlyAPI.bitlyStatsResponse)
                End Using

            Catch ex As Exception
                Throw New ApplicationException("API Error: " & ex.Message)
            End Try
            If responseObj.errorCode > 0 Then
                Throw New ApplicationException("Error from bit.ly: " & responseObj.errorMessage)
            End If
            Return responseObj
        End Function

    End Class

    Public MustInherit Class bitlyResponseBase
        <Xml.Serialization.XmlElement("errorCode")> _
        Public errorCode As Integer = 0

        <Xml.Serialization.XmlElement("errorMessage")> _
        Public errorMessage As String = String.Empty

        <Xml.Serialization.XmlElement("statusCode")> _
        Public statusCode As String = String.Empty

    End Class

    <System.Serializable(), Xml.Serialization.XmlRoot("bitly")> _
    Public Class bitlyShortenResponse
        Inherits bitlyResponseBase

        <Xml.Serialization.XmlArray("results"), Xml.Serialization.XmlArrayItem("nodeKeyVal")> _
        Public results As New List(Of KeyVal)

        Public Class KeyVal
            <Xml.Serialization.XmlElement("userHash")> _
             Public userHash As String

            <Xml.Serialization.XmlElement("shortKeywordUrl")> _
             Public shortKeywordUrl As String

            <Xml.Serialization.XmlElement("hash")> _
             Public hash As String

            <Xml.Serialization.XmlElement("nodeKey")> _
             Public longUrl As String

            <Xml.Serialization.XmlElement("shortUrl")> _
             Public shortUrl As String

        End Class
    End Class

    <System.Serializable(), Xml.Serialization.XmlRoot("bitly")> _
    Public Class bitlyInfoResponse
        Inherits bitlyResponseBase

        <Xml.Serialization.XmlArray("results"), Xml.Serialization.XmlArrayItem("doc")> _
        Public results As New List(Of bitlyInfoResultItem)

        Public Class bitlyInfoResultItem
            <Xml.Serialization.XmlElement("shortenedByUser")> _
            Public shortenedByUser As String
            <Xml.Serialization.XmlElement("keywords")> _
            Public keywords As String
            <Xml.Serialization.XmlElement("hash")> _
            Public hash As String
            <Xml.Serialization.XmlElement("exif")> _
            Public exif As String
            <Xml.Serialization.XmlElement("surbl")> _
            Public surbl As String
            <Xml.Serialization.XmlElement("contentLength")> _
            Public contentLength As String
            <Xml.Serialization.XmlElement("id3")> _
            Public id3 As String
            <Xml.Serialization.XmlElement("calais")> _
            Public calais As String
            <Xml.Serialization.XmlElement("longUrl")> _
            Public longUrl As String
            <Xml.Serialization.XmlElement("version")> _
            Public version As String
            <Xml.Serialization.XmlElement("htmlMetaDescription")> _
            Public htmlMetaDescription As String
            <Xml.Serialization.XmlElement("htmlMetaKeywords")> _
            Public htmlMetaKeywords As String
            <Xml.Serialization.XmlElement("calaisId")> _
            Public calaisId As String
            <Xml.Serialization.XmlElement("thumbnail")> _
            Public thumbnail As thumbnailObj
            <Xml.Serialization.XmlElement("contentType")> _
            Public contentType As String
            <Xml.Serialization.XmlArray("users"), Xml.Serialization.XmlArrayItem("item")> _
            Public users As List(Of String)
            <Xml.Serialization.XmlElement("globalHash")> _
            Public globalHash As String
            <Xml.Serialization.XmlElement("htmlTitle")> _
            Public htmlTitle As String
            <Xml.Serialization.XmlElement("metacarta")> _
            Public metacarta As String
            <Xml.Serialization.XmlElement("mirrorUrl")> _
            Public mirrorUrl As String
            <Xml.Serialization.XmlElement("keyword")> _
            Public keyword As String
            <Xml.Serialization.XmlElement("calaisResolutions")> _
            Public calaisResolutions As String
            <Xml.Serialization.XmlElement("userHash")> _
            Public userHash As String

            Public Class thumbnailObj
                <Xml.Serialization.XmlElement("large")> _
                Public large As String
                <Xml.Serialization.XmlElement("small")> _
                Public small As String
                <Xml.Serialization.XmlElement("medium")> _
                Public medium As String
            End Class

        End Class
    End Class

    <System.Serializable(), Xml.Serialization.XmlRoot("bitly")> _
Public Class bitlyStatsResponse
        Inherits bitlyResponseBase

        <Xml.Serialization.XmlElement("hash")> _
        Public hash As String
        <Xml.Serialization.XmlElement("clicks")> _
        Public clicks As String

        Public Class bitlyStatsResultItem
            <Xml.Serialization.XmlElement("None")> _
            Public None As String
            <Xml.Serialization.XmlElement("direct")> _
            Public direct As String
            <Xml.Serialization.XmlArray("nodeKeyVal"), XmlArrayItem("nodeKeyVal")> _
            Public nodeKeyValue As List(Of KeyValue)
            <Xml.Serialization.XmlElement("nodeKey")> _
            Public nodeKey As String

            Public Class KeyValue
                <Xml.Serialization.XmlElement("nodeValue")> _
            Public nodeValue As String
                <Xml.Serialization.XmlElement("nodeKey")> _
                Public nodeKey As String
            End Class
        End Class
    End Class

End Namespace

, , , , ,

Comments are closed.