Twitter API integration

Posted August 4th, 2009 by

Introduction

I’ve been building web, mobile, desktop apps that are powered by the ScreamingToaster ONE Platform for the last 3 years. I’ve had to integrate with a lot of services, like weather, credit card payment processing gateways, GeoIP lookups, CellID lookups, etc. One of the easiest integrations I’ve had to perform is with Twitter :) . Twitter has a simple to use API that can be accessed using Java or just about any other language. There are some really good Java wrappers for this API, and I’m going to highlight a really good one in this tutorial. I’m also going to show you how to integrate with Twitpic using Java.

Instead of building Twitter apps just for Twittering, my approach with ScreamingToaster software has been to leverage Twitter as a messaging service; another messaging service is email, for example. So in ScreamingToaster apps, many different things can be tweeted. For eg, in Wicked Blogging App for BlackBerry, you can take your status message and icon (that you snap using your BB camera with 1-Click) and tweet it – the status message is tweeted as your Twitter status update, and the icon you take from your BlackBerry camera with 1-Click is sent to Twitpic. Similarly, in Mylisty for BlackBerry and Web, you can take a todo list item and tweet it as your status. And so on.

Twitter API integration from Java

Twitter has a nice REST web API that is relatively straightforward to connect to using Apache HttpClient. However, there’s a much easier way to connect. Use this Java based API from Winterwell Associates. It’s a joy to use, it works, has great documentation, and comes with source code. What more could you ask for? Btw, the whole library is available as 1 JAR file, that barely has any dependencies, so you can easily import it into your project. Some other libraries I’ve wasted my time with have required hours to just import them! So save yourself some time, and go with this API.

Using it is ridiculously simple. Let’s say you wanted to take a string and tweet it. Well, this is how you might go about it:

String message = "your message string goes here";
String username = "tuser";
String password = "tpwd";

if (message.length() > 140) {
  message.substring(0, 140);
}

// Make a Twitter object
Twitter twitter = new Twitter(username, password);
// Set my status
Twitter.Status status = twitter.updateStatus(message);
if (status.getText().equals(message)) success = true;
else success = false;

As you can see in this code, you pass it a message string, which is truncated to 140 chars if it’s greater in length than that. Then the message is tweeted using the username and password that you provide. Once the status is updated, a quick check is performed to make sure that your status was indeed published.

If you want to do more with the API, then it has a lot more to offer. Check out the API docs and have fun!

Twitpic API integration from Java

Twitpic has a nice web API to allow you to HTTP POST pictures to it. The HTTP POST method needs to provide the input parameters as multipart/form-data. There are 4 params that must be provided: media (binary image data), username, password, message (optional). The code below uses the Apache HttpClient library to create this multipart/form-data POST operation to Twitpic URI.

/** @see <a href="http://twitpic.com/api.do">Twitpic api</a> */
public void twitpic(String username, String password, byte[] iconBytes) throws IOException {

    HttpClient client = Utils.getHttpClient();

    PostMethod method = new PostMethod("http://twitpic.com/api/uploadAndPost");

    ArrayList<Part> partList = new ArrayList<Part>();
    {
      partList.add(new StringPart("username", username));
      partList.add(new StringPart("password", password));
      partList.add(new StringPart("message", "My status icon - "));
      partList.add(new FilePart("media",
                                new ByteArrayPartSource("image.png", _convertToPNG(iconBytes)), "image/png", null
      ));
    }

    MultipartRequestEntity entity = new MultipartRequestEntity(
        partList.toArray(new Part[0]), method.getParams()
    );

    method.setRequestEntity(entity);
    client.executeMethod(method);

}

/** given any byte[] containing an image (gif/jpg/png/etc), will convert it to a png image */
private byte[] _convertToPNG(byte[] imgBytes) throws IOException {
  BufferedImage bufimg = ImageIO.read(new ByteArrayInputStream(imgBytes));
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  ImageIO.write(bufimg, "png", baos);
  baos.flush();
  return baos.toByteArray();
}

This is what’s happening in the code:

  1. A PostMethod is created with the POST URI for Twitpic
  2. A list of Parts is created that holds 1 FilePart object, and 3 StringPart objects. The StringPart objects contain the username, password, and message. The FilePart contains the binary image data. In my example, the image data is loaded from a byte[], but you can provide a File source as well to load the image data from. The image data can be PNG, JPG, GIF, etc. encoded. However, I convert it to PNG format before I send it to Twitpic.
  3. Once the multipart request entity is created with the StringParts and FilePart, I POST it to the Twitpic server.

Pretty straightforward, except for the PNG encoding at the end, and creating the FilePart from a ByteArrayPartSource. Let me know what projects/apps/services you are using Twitter/Twitpic integration in. Enjoy!

Comments/Feedback

Please leave them here if you have any.


Comments are closed.