Wednesday, January 12, 2011

Java: REST with ease :)

Update: you can get the latest Http client from Maven central:
http://search.maven.org/#search|gav|1|g%3A%22org.javalite%22%20AND%20a%3A%22javalite-common%22

Ever wanted to just send an HTTP request from Java? What should be easy is actually not. There are myriads of ways to do this in Java; you can write a half of page of ugly code with exceptions, use Apache HTTPClient library (which has its own dependencies), find another library, learn its API, etc. I told myself: "... but I just need to call a service and get a reply back!".
Eventually I got tired of this situation, and wrote my own tiny library for doing this: JavaLite.

Here is an example. If all you need is to send a GET request and get a response back, you could do this in one line:
Get get = Http.get("http://yahoo.com");
System.out.println(get.text());
System.out.println(get.headers());
System.out.println(get.responseCode());
The implementation has no dependencies and relies solely on standard Java API. The library even sets sensible defaults for timeouts. Also supports POST, DELETE and PUT.
The reason I developed it is because we are heavily relying on using REST services and a simple call to a service is really a must have.
So, an example of a service call would look like this:
if(Http.post("http://host/context/resources", postContent).text().equals("OK")){
    //..success
else{
    //failure
}
Eat that, SOAP! The code is so unobtrusive, sometimes it is hard to see. Oh, boy, I can breath now... head is cool, feet are warm...live is better now :)
Happy coding!
igor