Sunday, February 22, 2009

Posting JSON with Commons HTTPClient and XStream

I recently had an occasion where I had to perform an HTTP POST with JSON data from a Java service class as oppose to Javascript. No amount of Google searches turned up the answer I was after. Here are the steps I took to do so:

STEP 1 - Handle HTTP Post
The project I am working we were already using Commons HTTPClient which has a PostMethod class that peforms an HTTP Post. Here is the code to setup the post:

HttpClient clientService = new HttpClient();
PostMethod post = new PostMethod();
post.setURI(new URI("http://yoururl" false));

Step 2 - Find JSON Converter
The best tool kit I found for handling JSON is a combination of XStream and Jettison. Following the XStream tutorial, I did the following:

// This ensure that we drop the root element
XStream xstream = new XStream(new JsonHierarchicalStreamDriver() {
public HierarchicalStreamWriter createWriter(Writer writer) {
return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE);


// Stream the class I want converted into JSON
xstream.alias("site", ProjectBean.class);

Step 3 - Post the JSON Stream
Next up, is putting the two together and posting the JSON.

// Model bean to stream
ProjectBean site = new ProjectBean();

post.setRequestHeader("Content-Type", "application/json");

// apply content-length here if known (i.e. from proxied req)
// if this is not set, then the content will be buffered in memory
post.setRequestEntity(new StringRequestEntity(xstream.toXML(site), "application/json", null));

// execute the POST
int status = clientService.executeMethod(post);

// Check response code
if (status != HttpStatus.SC_OK) {
throw new Exception("Received error status " + status);

That is all there. I hope this helps.