java Gwt 请求构建器 - 如何返回响应字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15446161/
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-10-31 19:37:27  来源:igfitidea点击:

Gwt Request builder - how to return the response string

javagwt

提问by Syam Kumar S

I need to implement a function that calls a web service and return the response.

我需要实现一个调用 Web 服务并返回响应的函数。

I tried

我试过

public String getFolderJson(String path) {  
           String result="initial_value";
           StringBuilder param = new StringBuilder();  
           param.append("?sessionId=").append(getSessionId());  
           param.append("&path=").append(path);  
           RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, "https://localhost/folder" + param);  
                   try {  
                        builder.sendRequest(null, new RequestCallback() {  
                        @Override  
                        public void onResponseReceived(Request request,
                                Response response) {  
                              result = response.getText();
                              System.out.println(response.getText());  
                                            //I need to return "result"   
                        }  
                        @Override  
                        public void onError(Request request, Throwable exception) {}  
                          });  
                    return result; //the result get returned before the response is recieved.So i am getting the return value "initial_value".
                   }      
                   catch (RequestException e) {}  
        return null;
    }

On calling getFolderJson()the web service is called succesfully. But resultis returned before the respnse is recieved. So I am getting the retunr value "initial_value".
How to return the value from the response when getFolderJson()function ?

在调用 getFolderJson()Web 服务时成功调用。但是result在收到响应之前返回。所以我得到了返回值“initial_value”。函数
时如何从响应中返回值getFolderJson()

采纳答案by Manolo Carrasco Mo?ino

GWT does not support synchronous Ajax, so you have to code your app using asynchronous pattern.

GWT 不支持同步 Ajax,因此您必须使用异步模式编写应用程序。

The low level object that GWT uses to perform the request is a XMLHttpRequest(except for old IE versions), and GWT always calls it's open()method with async set to true. So the only way to have synchronous ajax is maintaining your own modified version of XMLHttpRequest.java. But synchronous ajax is a bad idea, and even jQuery has deprecated this possibility.

GWT 用于执行请求的低级对象是XMLHttpRequest(旧 IE 版本除外),并且 GWT 始终调用它的open()方法并将 async 设置为 true。因此,同步 ajax 的唯一方法是维护您自己的XMLHttpRequest.java. 但是同步 ajax 是一个坏主意,甚至 jQuery 已经弃用了这种可能性。

So the normal way in gwt should be that your method returns void, and you passes an additional parameter with a callback to execute when the response is available.

因此,gwt 中的正常方式应该是您的方法返回void,并且您传递一个带有回调的附加参数以在响应可用时执行。

public void getFolderJson(String path, Callback<String, String> callback) {  
    RequestBuilder builder = new RequestBuilder(...);
    try {
      builder.sendRequest(null, new RequestCallback() {  
        @Override  
        public void onResponseReceived(Request request, Response response) {
          callback.onSuccess(response.getText());  
        }  
        @Override  
        public void onError(Request request, Throwable exception) {}
          callback.onFailure(exception.getMessage());  
        });
    } catch (RequestException e) {
        callback.onFailure(exception.getMessage());  
    }  
}

I'd rather gwtquery Promisessyntax for this instead of request-builder one:

我宁愿为此使用 gwtqueryPromises语法而不是请求构建器之一:

  Ajax.get("http://localhost/folder?sessionId=foo&path=bar")
    .done(new Function(){
      public void f() {
        String text = arguments(0);
      }
    });

回答by BlackJoker

I guess the builder.sendRequest(xxx) will return something like a Future,and you can get the result from that object.What you are using is an asynchronous method of RequestBuilder,there should be some synchronous method as well.

我猜 builder.sendRequest(xxx) 会返回类似 Future 的东西,你可以从那个对象中得到结果。你使用的是 RequestBuilder 的异步方法,也应该有一些同步方法。

what does RequestBuilder come from? I can check the api for you.

RequestBuilder 来自什么?我可以帮你查一下api。

OK,try this:

好的,试试这个:

public String getFolderJson(String path) {
    String result = "initial_value";
    StringBuilder param = new StringBuilder();
    param.append("?sessionId=").append(getSessionId());
    param.append("&path=").append(path);
    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET,
            "https://localhost/folder" + param);
    final SynchronousQueue resultQueue = new SynchronousQueue();
    try {
        builder.sendRequest(null, new RequestCallback() {
            @Override
            public void onResponseReceived(Request request,
                    Response response) {
                resultQueue.put(response.getText());
                System.out.println(response.getText());
            }

            @Override
            public void onError(Request request, Throwable exception) {
            }
        });
        return resultQueue.take();
    } catch (RequestException e) {
    }
    return result;
}

It seems RequestBuilderdoes not have any Synchronous method to get the result only a callback.

似乎RequestBuilder没有任何 Synchronous 方法来仅通过回调获取结果。

Be careful this method will block until the response is recieved. If this method is called in an event processing thread of gwt,this would be a bad practice.

请注意,此方法将阻塞,直到收到响应。如果在 gwt 的事件处理线程中调用此方法,这将是一个不好的做法。

回答by Alicia

Try the same solution offered above except not with an anonymous Callback.

尝试上面提供的相同解决方案,但不使用匿名回调。

public String getFolderJson(String path) { 

    RequestBuilder builder = new RequestBuilder(...);
    HttpCallback cb=new HttpCallback();

    try {
      builder.sendRequest(null, cb);
    } catch (RequestException e) {
    // exception handling
        logger.severe(cb.err);
    }  

    return cb.result;
}

class HttpCallback implements RequestCallback{

    String result;
    String err;

    HttpCallback(){}

    @Override
    public void onResponseReceived(Request request, Response response) {            
        result=response.getText());     
    }

    @Override
    public void onError(Request request, Throwable exception) {
        err=exception.getMessage();     
    }       
}