我需要实现一个调用Web服务并返回响应的函数.
我试过了
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; }
调用getFolderJson()Web服务被成功调用.但结果在收到之前返回.所以我得到了retunr值“initial_value”.
当getFolderJson()函数时如何从响应中返回值?
解决方法
GWT不支持同步Ajax,因此您必须使用异步模式对应用进行编码.
GWT用于执行请求的低级对象是XMLHttpRequest(除了旧版本的IE版本),而GWT总是将async设置为true来调用它的open()方法.所以,同步ajax的唯一方法就是维护你自己修改的XMLHttpRequest.java版本.但是同步的ajax是一个坏主意,甚至jQuery已经不赞成这种可能性.
所以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()); } }
我宁愿gwtquery Promises语法,而不是请求构建器一:
Ajax.get("http://localhost/folder?sessionId=foo&path=bar") .done(new Function(){ public void f() { String text = arguments(0); } });