Shortening URLs With The bit.ly API Via ASP.NET
After yesterday’s post on using the Twitter API to post status updates on Twitter from an ASP.NET application, a follower of my client suggested using a URL shortening service to link to the articles headlines being posted as tweets.
That was an excellent idea of which I should have thought in the first place. And thanks to the extreme simplicity of the REST-like bit.ly API, shortening URLs is as simple as sending a request URL laced with querystring variables.
So here is a quick and simple ASP.NET subroutine, written in VB.NET, to shorten URLs with the bit.ly API:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | Sub BitlyIt(ByVal strUser As String, ByVal strAPIKey As String, ByVal strLongUrl As String) 'build URL to shorten method resource Dim strUri As New StringBuilder("http://api.bit.ly/shorten?") strUri.Append("version=2.0.1") 'we want to get an XML response back from bit.ly, not the default JSON strUri.Append("&format=xml") strUri.Append("&longUrl=") strUri.Append(Server.HtmlEncode(strLongUrl)) strUri.Append("&login=") strUri.Append(Server.HTMLEncode(strUser)) strUri.Append("&apiKey=") strUri.Append(Server.HTMLEncode(strAPIKey)) '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 bit.ly 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() objXML.Load(objResponse.GetResponseStream()) '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 Else lblStatus.Text = nShortUrl.InnerText End If End Sub |
Continue reading ‘Shortening URLs With The bit.ly API Via ASP.NET’ »
