如何从GWT调用RESTFUL服务?

25
我正在使用GWT作为Web开发框架。 我需要从我的GWT客户端代码访问一些REST服务。此外,我需要解析JSON(或可能是XML),这是这些服务的响应格式。对于这个问题,哪种方式最好?
提前致谢。
6个回答

18

您可以使用标准的GWT RequestBuilder(如果需要调用另一个域上的服务,则使用JsonpRequestBuilder)来调用REST服务。

通过JSON响应字符串,您可以调用JSONParser.parseStrict(jsonString)来获取JSONValue,它可以是JSONObjectJSONArray等。这些都在此包中提供。


8

您可以通过创建代理服务接口,在 GWT 应用程序中使用 RestyGWT 调用 Restful web 服务:

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

或者当您不想费力创建服务接口时:

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

它还拥有方便的API,可以将Java对象编码和解码成JSON格式。

2
以下代码使用RequestBuilder在GWT中向RESTFUL Webservice发送请求:
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();
}

2

RequestBuilder 是一种低级别的方法,用于进行 HTTP 请求。

您可以使用更高级别的方法,使用Turbo GWT HTTP来方便地管理客户端与服务器之间的通信并流畅地执行请求。

它更适合 REST 风格的通信。考虑以下示例:

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

在调用REST服务之前,无需对其进行映射(这在RPC通信中是概念上所需的,但在REST中不需要)。您可以根据需求随时使用您的服务。


2

对于REST服务:请查看gwt-rest

关于GWT的JSON支持:请参见这里


restful-gwt如何调用restful服务。我在项目文档中没有看到示例。 - ovunccetin

0

对于这个问题,我发现使用GWT JSNI更容易。

例如,调用JSON服务以获取用户的国家代码:

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

"Loaded" 只是:

package mypackage;

public interface Loaded<T> {
    public void data(T data);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接