开发者

How to call RESTFUL services from GWT?

开发者 https://www.devze.com 2023-01-21 09:01 出处:网络
I\'m using GWT as web development framework. I need to access some REST services from my G开发者_JS百科WT client code. Also I need to parse JSON (or maybe XML) which is response format of these servic

I'm using GWT as web development framework. I need to access some REST services from my G开发者_JS百科WT 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.


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.


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.


For REST services: checkout gwt-rest.

For JSON support in GWT: see here


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.


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


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

精彩评论

暂无评论...
验证码 换一张
取 消