TweetPhoto API tutorial in VB.NET

November 11, 2009 by · 5 Comments 

I’ve already told you that I am currently working on a Twitter client with two other guys as part of a college project. Along with URL shortening, Tweeting photos seems to be a fairly common feature in other clients so it’s also something we must fully support in our client, JACTweet!!

I will be using the tweetPhoto service to tweet photos. API documentation starts here but keep in mind that you must apply for an API key before you start. Application is currently by e-mail (not automated) so you should apply for a key straight away before you even start reading the documentation.

I would also suggest using some kind of HTTP debugger when familiarizing yourself with web service interfaces. I am currently using Fiddler and can only say good things about it. It lets you see the raw data that is being sent accross the interent and more importantly what the web server on the other side sees.

I’ll start off by stepping you through what needs to be done:

  1. Creat a new instance HTTPWebRequest
  2. Set method (POST) and add headers – Except for content length, which is unknown at this point
  3. Read image file into a byte array (Note: TweetPhoto 5MB limit)
  4. Set content-length header to the length of above byte array
  5. Stream file (byte array) to tweetPhoto
  6. Get response from tweetPhoto

First we create a new instance of HTTPWebRequest with the tweetPhoto API upload URL. Adding method and known headers also.

Dim request = HttpWebRequest.Create("http://tweetphotoapi.com/api/tpapi.svc/upload2")
        request.Method = "POST"
        request.ContentType = "application/x-www-form-urlencoded"
        request.Headers.Add("TPAPIKEY: api_key_here")
        request.Headers.Add("TPAPI: username,password")
        request.Headers.Add("TPMIMETYPE: image/png")
        request.Headers.Add("TPPOST:True")
        request.Headers.Add("TPMSG: message here")
        request.Headers.Add("TPTAGS: comma,seperated,tags,here")

Next we will read the image file into a byte array and set the content-length header.

Dim content() = File.ReadAllBytes("path_to_image_file_here")
request.ContentLength = content.Length

Now we will stream the actual image file to tweetPhoto in the form of bytes. If you are thinking in terms of the HTTP transmission then this is the body and everything else beforehand has just been headers telling the web servers what to expect in the body.

Using str As System.IO.Stream = request.GetRequestStream()
          str.Write(content, 0, content.Length)
End Using

If you’ve gotten this far then the above code is working perfectly without any exceptions. We conclude with the response from the server. This comes in the form of XML but for now we’ll just save it as a string.

Dim response = request.GetResponse()
Dim responseOutput as String

Dim reader As StreamReader
reader = New StreamReader(response.GetResponseStream())
responseOutput = reader.ReadToEnd()

For clarity here is all the above code in just one block.

       'Imports System.IO -> Required
       'Imports System.Net -> Required

        Dim request = WebRequest.Create("http://tweetphotoapi.com/api/tpapi.svc/upload2")
        request.Method = "POST"
        request.ContentType = "application/x-www-form-urlencoded"
        request.Headers.Add("TPAPIKEY: your_api_key_here")
        request.Headers.Add("TPAPI: password,username")
        request.Headers.Add("TPMIMETYPE: image/png")
        request.Headers.Add("TPPOST:True")
        request.Headers.Add("TPMSG: message here.")
        request.Headers.Add("TPTAGS: comma,seperated,tags,here")

        Dim content() = File.ReadAllBytes("path_to_image_here")
        request.ContentLength = content.Length

        Using str As System.IO.Stream = request.GetRequestStream()
            str.Write(content, 0, content.Length)
        End Using

        Dim response = request.GetResponse
        Dim responseOutput As String

        Dim reader As StreamReader
        reader = New StreamReader(response.GetResponseStream())
        responseOutput = reader.ReadToEnd()
        MessageBox.Show(responseOutput)

I have also made up a quick demo that uploads a photo along with tags and a message to a users account. You can get the source here. The source is in Visual Studio 2008 Pro format.

Have fun!

Oh, and if somebody actually reads this and finds it useful then please post a comment to let me know what you think. It would be amazing to see people actually reading this blog.:-)

Shorten URLs in Visual Basic using Bit.ly API

November 3, 2009 by · Leave a Comment 

I’m currently working on a Twitter client for college that will provide a function to shorten URLs using the Bit.ly API.

It’s actually really simple and easy to use and while my sample interface is written in VB you can use the API with any language. To use the API all you need do is construct a URL like so:

http://api.bit.ly/shorten?version=2.0.1&longUrl=http://www.conorhackett.com&login=[USERNAME]&apiKey=[API_KEY]

You will need to register with Bit.ly to get API key and a username before you can try this. Also, the url you want to shorten must begin with “http://” or else you will get an error. The above URL (with my API key included) will return the following response:

{ “errorCode”: 0, “errorMessage”: “”, “results”: { “http://www.conorhackett.com”: { “hash”: “nzIzC”, “shortKeywordUrl”: “”, “shortUrl”: “http://bit.ly/9SWQS”, “userHash”: “9SWQS” } }, “statusCode”: “OK” }

From this you can extract the shortened URL along with the status of the response among other but they are the only two pieces of information that I used.

Below you’ll find my solution written in VB. The handling of the status messages isn’t the greatest but it works fine. I should really be using regular expressions to validate user input and extract information from the response. It’s late and my regex skills are still a little shaky so i’ll leave that until another day. :-)

    ' NOTE: you must use -> Imports  System.Net

    Public Function getShort(ByVal url As String) As String
        ' New instance of WebClient
        Dim client As WebClient = New WebClient()
        ' if URL doesn't start with http:// then append it to the start
        If url.StartsWith("http://") = False Then
            url = "http://" + url
        End If

        ' Setup command url to be sent to Bit.ly API
        Dim commandUrl As String = "http://api.bit.ly/shorten?version=2.0.1&longUrl=" + url + "&login=[USERNAME]&apiKey=[API_KEY]"
        ' Get raw result string
        Dim result As String = client.DownloadString(commandUrl)

        ' Determine status of repsonse
        ' This needs to be improves but works ok for now.
        If result.IndexOf("""statusCode"": ""OK""") > 0 Then
            ' Get position of the beginning of short URL.
            Dim indexOf As Integer = result.IndexOf("http://bit.ly/")
            result = result.Substring(indexOf, 19)
        End If
        If result.IndexOf("""statusCode"": ""ERROR""") > 0 Then
            ' Throw an exception if response is ERROR.
            Throw New System.Exception("ERROR")
        End If

        Return result
    End Function

Update: This tutorial focuses on getting a JSON formatted response from Bit.ly. This can be changed to XML by adding &format=xml at the end of the request URL. I will post a guide on working with XML in the near future.