Shortening URLs With The API Via ASP.NET

A subroutine to leverage the API to shorten fully qualified URLs. Requires the System.IO, System.XML and System.Net namespaces.

Code Behind

        Sub BitlyIt(ByVal strUser As String, ByVal strAPIKey As String, ByVal strLongUrl As String)
	        'This subroutine requires your page to have a label control named lblStatus
	        'build URL to shorten method resource
	        Dim strUri As New StringBuilder("")
	        'we want to get an XML response back from, not the default JSON
	        'create request for shorten resource
	        Dim objRequest As HttpWebRequest = WebRequest.Create(strUri.ToString())
	        'since we are passing querystring variables, our method is get
	        objRequest.Method = "GET"
	        'act as though we are sending a form
	        objRequest.ContentType = "application/x-www-form-urlencoded"
	        'don't wait for a 100 Continue HTTP response from
	        objRequest.ServicePoint.Expect100Continue = False
	        'since we are using get, we need not send a request body; set content-length to 0
	        objRequest.ContentLength = 0
	        'we need to capture the XML being sent in response 
	        'read the response into a new XML document
	        Dim objResponse As WebResponse = objRequest.GetResponse()
	        Dim objXML As New XmlDocument()
	        'the response will have three node values we're primarily interested in
	        'the errorCode node will contain a numeric error code; 0 means success
	        Dim nErrorCode As XmlNode = objXML.SelectSingleNode("//errorCode")
	        'if there was an error, the errorMessage node will contain a user-friendly message useful for debugging
	        Dim nErrorMsg As XmlNode = objXML.SelectSingleNode("//errorMessage")
	        'if all went well, shortUrl will contain the full short URL created for our link
	        Dim nShortUrl As XmlNode = objXML.SelectSingleNode("//shortUrl")
	        'if we didn't get an errorCode value of 0, there was a problem; report the user-friendly message
	        'on success, report the short URL for our resource
	        If nErrorCode.InnerText <> "0" Then
		        lblStatus.Text = "Error returned. Code: " & nErrorCode.InnerText & "; Message: " & nErrorMsg.InnerText
		        lblStatus.Text = nShortUrl.InnerText
	        End If
        End Sub