Jose Sandoval Google
 Resume     Book     Software     Drawings     Home     Subscribe to RSS feed Search Web Search

Using the Restlet client connector library
Thursday, August 20, 2009

The Restlet framework does not only offer a server stack for developing web services, it also offers a client connector library, which can be used to develop clients connecting to RESTful web services or any other web application.

Let's just get to the code, because all it takes is 1 line to do the whole thing.

For this example, we'll connect to Twitter's URI, which returns the last 20 public statuses as an XML structure. The code looks as follows:
import org.restlet.resource.ClientResource;
import org.restlet.resource.ResourceException;

public class StandAloneClient {
public static void main(String[] args) {
try {
new ClientResource(
} catch (IOException e) {
} catch (ResourceException e) {
All we need to provide the ClientResource class's constructor is the URI, then we call the get() method, and, for this example, we just print the result to the out stream, which looks as follows (part of it; the XML structure is too long):

<?xml version="1.0" encoding="UTF-8"?>
<statuses type="array">
<created_at>Thu Aug 20 15:29:48 +0000 2009</created_at>
<text>(Cont)Returned but From Now on Its all About Byron B. Seriously I honestly care less about other people.Cont. to be in the same boat!(Cont)

If you recall, the Java net package already has code to open connections over the web. Do we need one more HTTP Client library? Sure, why not.

On the plus side, this Restlet client library provides some extras that make RESTful client development easier. For example, the ClientResource class includes methods for the other HTTP request types (POST, PUT, DELETE). Having these methods already understand REST means that we can pass representations back and forth without manually setting HTTP headers for automatic content negotiation. Mind you that it's not hard to open an HTTP connection, send a request, and consume its response; however, if everything is already wrapped conveniently into a few methods, why go through the pain of adding more code when we can do everything with 1 statement?

If you want to compile and run this sample application, download and unpack the the Restlet package. Then, compile the app with:
javac -cp "RESTLET_INSTALL/org.restlet.jar"

And run it with:
java -cp "RESTLET_INSTALL/org.restlet.jar" StandAloneClient

11:26 AM | 0 comment(s) |


This page is powered by Blogger. Isn't yours?

© Jose Sandoval 2004-2009