How to access Web Services with GWT

February 6th, 2008 - Written by in Using GWT

There are a lot of new and interesting web services popping up on the web these days, and you may want to make use them in your GWT applications. In this short guide, I will show you how to call these public apis from within your GWT app.

The main difficulty when trying to talk to some web service on another server is getting past your web browser’s Same-Origin Policy. This basically says that you may only make calls to the same domain as the page you are on. This is good for security reasons, but inconvenient for you as a developer as it eliminates the use of GWT’s HTTP library functions to achieve what we want to do. One way to get around this is to call a web service through a javascript tag which bypasses this problem. In his book, Google Web Toolkit Applications, Ryan Dewsbury actually explains this technique in more detail and provides a class called JSONRequest which handles all the hard work for us. JSON is one of the more popular data formats, so most web services support it. Lets leverage Ryan’s code and take a quick look at how it works.

public class JSONRequest {
  public static void get(String url, JSONRequestHandler handler) {
    String callbackName = "JSONCallback"+handler.hashCode();
    get( url+callbackName, callbackName, handler );
  }   
  public static void get(String url, String callbackName, JSONRequestHandler handler ) {
    createCallbackFunction( handler, callbackName );
    addScript(url);
  }
  public static native void addScript(String url) /*-{
    var scr = document.createElement("script");
    scr.setAttribute("language", "JavaScript");
    scr.setAttribute("src", url);
    document.getElementsByTagName("body")[0].appendChild(scr);
  }-*/;
  private native static void createCallbackFunction( JSONRequestHandler obj, String callbackName)/*-{
    tmpcallback = function(j) {
      ::onRequestComplete(Lcom/google/gwt/core/client/JavaScriptObject;)(j);
    };
    eval( "window." + callbackName + "=tmpcallback" );
  }-*/;
}

To make our request we call the get method with the web service url, and an implementation of the JSONRequestHandler interface. This interface has one method called onRequestComplete(String json). This is where you’ll handle the JSON formatted data once it comes back from the server. When calling a service from within a script tag, we need to specify the name of a callback function in the request. Most services let you specify the name yourself, so the first get method generates a callback name for you. The createCallback method is a JSNI method that simply calls your JSONRequestHandler implementation when the call returns via the callback name. Note, if you use this class, to make sure and change the package name for the JSONRequestHandler call to the correct location. Finally, the get method will call the addScript function which is responsible for embedding the