25

I'm using GWT as web development framework. I need to access some REST services from my GWT client code. Also I need to parse JSON (or maybe XML) which is response format of these services. Which is the best way for this problem?

Thanks in advance.

ovunccetin
  • 8,443
  • 5
  • 42
  • 53

6 Answers6

18

You can call REST services using the standard GWT RequestBuilder (or JsonpRequestBuilder if you need to call services on another domain).

With the JSON response string, you can call JSONParser.parseStrict(jsonString) to get a JSONValue, which can be a JSONObject, JSONArray, etc. This is all available in this package.

Martin Pain
  • 713
  • 4
  • 18
Jason Hall
  • 20,632
  • 4
  • 50
  • 57
8

You can easily call a Restful web services using RestyGWT in your GWT application by creating proxy service interface:

import javax.ws.rs.POST;
...
public interface PizzaService extends RestService {
    @POST
    public void order(PizzaOrder request, 
                      MethodCallback<OrderConfirmation> callback);
}

or when you don't want to go through the trouble of creating service interfaces:

Resource resource = new Resource( GWT.getModuleBaseURL() + "pizza-service");

JSONValue request = ...

resource.post().json(request).send(new JsonCallback() {
    public void onSuccess(Method method, JSONValue response) {
        System.out.println(response);
    }
    public void onFailure(Method method, Throwable exception) {
        Window.alert("Error: "+exception);
    }
});

It has also got nice API for encoding and decoding Java Object to JSON.

Saeed Zarinfam
  • 9,818
  • 7
  • 59
  • 72
2

RequestBuilder is a low-level approach to make HTTP requests.

You can resort to a higher level approach working with Turbo GWT HTTP, a convenient API for managing client-server communication and performing requests fluently.

It fits better the REST style communication. Consider the following example:

Request request = requestor.request(Void.class, Book.class)
        .path("server").segment("books").segment(1)
        .get(new AsyncCallback<Book>() {
            @Override
            public void onFailure(Throwable caught) {

            }

            @Override
            public void onSuccess(Book result) {
                Window.alert("My book title: " + result.getTitle());
            }
});

There's no need to map your REST services before calling them (which is conceptually required for RPC communication, but not for REST). You can just consume your services on demand.

reinert
  • 50
  • 4
2

The below source of code used RequestBuilder to post a request to RESTFUL Webservice using GWT

JSONObject jsonObject = new JSONObject();

email = (String) vslLoginView.getFieldUserEmailID().getValue();
password = (String) vslLoginView.getFieldUserPasword().getValue();

jsonObject.put("email", new JSONString(email));
jsonObject.put("password", new JSONString(password));
System.out.println("Password at Presenter:"
    + jsonObject.get("password"));
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST,
    RecursosURL.LOGIN.toString()/*your restful webservice url */ + "/authenticateuser");
builder.setHeader("Content-Type", "application/json");
try {
    SC.showPrompt(constants.wait());
    builder.sendRequest(jsonObject.toString(),
        new SamrtWebRequestCallback(false, false, false, false) {

            @Override
            public void onSuccess(Response response) {
                // Recevie response of logged user data from  restful webservice
                JSONObject jsonOnlineUser = JSONParser.parse(
                    response.getText()).isObject();
                UserTO userTO = ConverterUser
                    .converterJSONParaUser(jsonOnlineUser);
                String primaryAccess = jsonOnlineUser.get(
                    "primaryAccess").isString().stringValue();

                HashMap<String, Object> parameters = new HashMap<String, Object>();
                if (primaryAccess.equals("S")) {

                    parameters.put("email", email);
                    parameters.put("password", password);
                    parameters.put("id", jsonOnlineUser.get("id")
                        .isString().stringValue());

                } else {

                    parameters.put("email", email);
                    handlerManager.fireEvent(new EvtIrParaPage(
                        Pages.PAGE_INICIAL, parameters));
                }

            }

            @Override
            protected void onErrorCallbackAdapter(Response response) {
                vslLoginView.getLabelMsgErro().setContents(
                    response.getText());
                vslLoginView.getLabelMsgErro().setVisible(true);
            }
        });

} catch (RequestException e) {
    e.printStackTrace();
}
Tunaki
  • 132,869
  • 46
  • 340
  • 423
2

For REST services: checkout gwt-rest.

For JSON support in GWT: see here

z00bs
  • 7,518
  • 4
  • 34
  • 53
0

For this stuff, I find it easier to fall back to using GWT JSNI.

Eg, Calling a JSON service to get the users country code:

public static native void getCountryCode(Loaded<String> countryCode) /*-{
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var jsonObj = JSON.parse(xhttp.responseText);
            countryCode.@mypackage.Loaded::data(*)(jsonObj.country_code);
        }
    };
    xhttp.open("GET", "https://api.ipdata.co/", true);
    xhttp.send();
}-*/;

Where "Loaded" is just:

package mypackage;

public interface Loaded<T> {
    public void data(T data);
}
Craigo
  • 3,384
  • 30
  • 22