Twitter provide a RESTful API that allows third party applications to access and use their services. In this post I’ll show you how to submit a status update using the this API from a Java application. To do this we’ll need to construct an HTTP POST request. In Java it’s not simple to do this so the code shown below is a little complex. On the plus side though, there’s not a lot of it.

The code:

import org.apache.commons.codec.binary.Base64;
import java.io.*;
import java.util.*;
import java.net.*;

//prepare a connection for the twitter API update method
URL url = new URL("http://twitter.com/statuses/update.xml");
URLConnection conn = url.openConnection();
conn.setAllowUserInteraction(false);
conn.setDoOutput(true);

//encode users credentials
byte[] credentialsBytes = (username +":" + password).getBytes();
byte[] encodedBytes = Base64.encodeBase64(credentialsBytes);
String credentialString = new String(encodedBytes);
conn.setRequestProperty("Authorization", "Basic " + credentialString);

//set the request to POST and send
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes("status=" + URLEncoder.encode(message, "UTF-8"));
out.flush();
out.close();

//get the response
BufferedReader input = new BufferedReader(
        new InputStreamReader(conn.getInputStream()));
StringBuilder builder = new StringBuilder();
String s = null;
while ((s = input.readLine()) != null) {
    builder.append(s);
}
input.close();
String response = builder.toString();

Prepare a request

First, a URL for Twitter’s status update method is created (line 7).

Authenticate the caller

Most of the methods in the Twitter API require the caller to authenticate. The simplest way to do this is to use HTTP BASIC authentication. To authenticate a user using BASIC authentication the client must construct a string with the users name and password separated by a colon. For example, for a Twitter user with a user name ‘fredsmith’ and a password ‘fredspassword’, the string should look like this:

fredsmith:fredspassword

the above should then be base 64 encoded (note that this example uses Apache Commons codec for this) before being prepended with the characters “Basic: “. Finally, the encoded credentials string must be set in the Authorization header of the request (lines 13-16). When the server receives the request it will extract the users name and password and authenticate them.

Use HTTP POST to send the status parameter

To ensure that the request is sent using POST, the Content-Type header is set (line 19).

Then, the status parameter can have its value UTF encoded and set (line 21).

Read the response message

Lines 25-33 read the response from Twitter, by default an XML document, that should confirm that the status for the user has been updated.

Get Twittering

The above code has been tested and proven to work in a production environment. If you want to use it yourself then please feel free (you can use the [<>] tool above the code to copy it). Any comments or suggestions on how it may be simplified or improved are welcomed.