如何从GWT调用RESTFUL服务?

时间:2010-10-27 07:48:08

标签: java rest gwt

我正在使用GWT作为Web开发框架。我需要从GWT客户端代码访问一些REST服务。此外,我需要解析JSON(或XML),这是这些服务的响应格式。哪个是解决这个问题的最佳方式?

提前致谢。

6 个答案:

答案 0 :(得分:17)

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

使用JSON响应字符串,您可以致电JSONParser.parseStrict(jsonString)以获取JSONValueJSONObjectJSONArray等等。{{1}} {3}}

答案 1 :(得分: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 Object到JSON。

答案 2 :(得分:2)

对于REST服务:checkout gwt-rest

对于GWT中的JSON支持:请参阅here

答案 3 :(得分:2)

RequestBuilder是一种发出HTTP请求的低级方法。

您可以采用更高级别的方法来处理Turbo GWT HTTP,这是一个方便的API,用于管理客户端 - 服务器通信和流畅地执行请求。

它更适合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)。您可以按需使用服务。

答案 4 :(得分: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();
}

答案 5 :(得分:0)

对于这些东西,我发现回归使用GWT JSNI更容易。

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

> str(time_series)
List of 9
 $ Germany    : Time-Series [1:52] from 1960 to 2011: 684721 716424 749838   ...
 $ Singapore  : Time-Series [1:52] from 1960 to 2011: 7208 7795 8349   ...
 $ Finland    : Time-Series [1:37] from 1975 to 2011: 85842 86137 86344   ...

在哪里&#34;加载&#34;只是:

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();
}-*/;
相关问题