ovunccetin
ovunccetin

Reputation: 8663

How to call RESTFUL services from GWT?

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.

Upvotes: 26

Views: 39403

Answers (6)

Craigo
Craigo

Reputation: 3717

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);
            [email protected]::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);
}

Upvotes: 0

Jason Hall
Jason Hall

Reputation: 20920

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.

Upvotes: 18

user4423251
user4423251

Reputation:

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();
}

Upvotes: 2

reinert
reinert

Reputation: 60

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.

Upvotes: 3

Saeed Zarinfam
Saeed Zarinfam

Reputation: 10180

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.

Upvotes: 8

z00bs
z00bs

Reputation: 7498

For REST services: checkout gwt-rest.

For JSON support in GWT: see here

Upvotes: 2

Related Questions