Tuesday, October 23, 2007

Groovy REST client with Apache httpclient (setting accept request-header value)

Been doing quite a bit with REST style services in Grails. In particular trying to follow closes REST best practices approaches. One of these approaches is to inspect the HTTP Accept header values. (Ref: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html).

While creating these services a person really needs a simple client that they can alter the accept request-header field with. I created one using the Apache httpclient package (http://jakarta.apache.org/httpcomponents/httpclient-3.x/).

Simply download and place the commons-httpclient-*.jar file into your groovy lib directory (or somewhere you class loader will find it) and generate a Groovy program like:

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.methods.GetMethod;

def url = "URL TO SERVICE"
client = new HttpClient()
get = new GetMethod(url)
get.setRequestHeader("Accept", "text/xml")

println get.getResponseBodyAsString().toString()

It's a simple client and one can alter the ACCEPT header value easily to check and validate REST services response to various settings of accept request-header.