Saturday, February 20, 2010

GWT client with REST

This article explains a small prototype i developed for a friend to show how REST services can be used can be used from the client code and avoid additional RPC call. The demo explains only two fundamental class structures to access the remote service.

RequestBuilder
GWT client API is having an HTTP request builder class which helps the application to make remote connection through HTTP request and supported methods (GET, POST).

RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, urlAddress);
builder.sendRequest("", new RequestCallback() {
  
  public void onResponseReceived(Request request, Response response) {
     //use response.getText() to get the resulting text from the service
  }


  public void onError(Request request, Throwable exception) {
     // exception handling
  }
});

XmlParser
GWT client API also provides XML parsing capabilities but to use that XML.gwt.xml has to be included in the modules file.

The following code can parse the XML text and prepare complex node list which can be traversed to access the attributes and node values.

    Document doc = XMLParser.parse(response.getText());

Once Document instance is generated program can start traversal from the root node or can search for the particular nodes based on the name.

    NodeList nodeList = doc.getChildNodes(); // to start from root node
    NodeList nodeList = doc.getElementsByTagName(nodeName);  // to start from selected node

Full source code with example services is available here.

3 comments:

  1. Hi,

    If you want to use restful services from GWT, then you should look into the RestyGWT project

    It uses some gwt generators to make restful services as easy to use as GWT RPC services.

    ReplyDelete
  2. Thanks Hiram,

    RestyGWT seems pretty cool.

    I m gonna use it with one of my GWT based Twitter client.

    I'll reply you the status.

    ReplyDelete
  3. Does RestGWT support XML? It looks like it just supports JSON. Can you provide an example of using it with an XML service using JAXB serialization?

    ReplyDelete