Java 如何从 GWT 调用 RESTFUL 服务?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4030969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 10:43:13  来源:igfitidea点击:

How to call RESTFUL services from GWT?

javarestgwt

提问by ovunccetin

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?

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

Thanks in advance.

提前致谢。

采纳答案by Jason Hall

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

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

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.

随着JSON响应字符串,你可以调用JSONParser.parseStrict(jsonString)获得JSONValue,它可以是一个JSONObjectJSONArray等等,这是在所有可用的这个包

回答by z00bs

For REST services: checkout gwt-rest.

对于 REST 服务:结帐gwt-rest

For JSON support in GWT: see here

有关 GWT 中的 JSON 支持:请参阅此处

回答by Saeed Zarinfam

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

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

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.

它还具有用于将 Java 对象编码和解码为 JSON 的良好 API。

回答by reinert

RequestBuilderis a low-level approach to make HTTP requests.

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

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.

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

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

它更适合 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());
            }
});

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.

在调用您的 REST 服务之前不需要映射它们(这在概念上是 RPC 通信所必需的,但不是 REST 所必需的)。您可以按需使用您的服务。

回答by reinert

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

下面的代码源使用 RequestBuilder 使用 GWT 向 RESTFUL Web 服务发布请求

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

回答by Craigo

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

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

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

例如,调用 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);
            [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);
}