Wednesday, September 2, 2009

How to download response, even if you get a HTTP 500

When we normally connect to a HTTP URL from within our java code, we tend to check only the status code and proceed based on its value. We'll be interested in handling only the HTTP SUCCESS code 200, but for other errors you'll simply want to report it as a 'Generic error'

But there're times, when you want to see what exactly does the server returned for our request for diagnostics purpose. For example, a monitoring server may not just want to know what error code the server has returned, but also want details about what exactly happened at the server side. I've written simple groovy script which uses the commons-http client and core modules from Apache to do this task for me.



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

client = new HttpClient()
method = new GetMethod("http://10.11.12.48:8004/monitor")
def statusCode = client.executeMethod(method)

println "Status code is : ${statusCode}"

//Read the response body.
byte[] responseBody = method.getResponseBody();

// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
println(new String(responseBody));

You should keep following files in the class path to run this program successfully.
  1. commons-httpclient.jar
  2. commons-codec.jar
  3. commons-logging.jar

And ofcourse, you can change the URL to which ever value you want to test out other error codes.

No comments: