我有我的REST服务:http://localhost:4242/myrestservice/getobject 它返回一些JSON数据
然后,我有我的GWT客户端: http://localhost:4242/gwtclient 该客户端应该对REST服务进行异步调用。
我是新手,所以我的第一个想法是做以下事情:
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode("http://localhost:4242/myrestservice/getobject"));
builder.setHeader("Accept", "application/json");
builder.setCallback(new MyObjectDescCallback());
builder.setRequestData("");
Request req = builder.send();
...
final class MyObjectDescCallback implements RequestCallback {
public void onError(Request request, Throwable exception) {
showAlert("error = "+exception.getMessage());
GWT.log(exception.getMessage());
}
public void onResponseReceived(Request request, Response response) {
showAlert("response = " + response.getStatusCode());
//Do my stuff here
}
}
}
不幸的是,我没有回复。
我检查了Rest服务,它确实发送了对象
似乎我的GWT应用程序没有得到答案。
知道如何让它发挥作用吗?
更新
以下是我使用Firebug的结果:
Response Headers
Server Apache-Coyote/1.1
Content-Type application/json
Transfer-Encoding chunked
Date Sun, 24 Apr 2011 11:04:15 GMT
Request Headers
Host 127.0.0.1:4242
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0
Accept application/json
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip, deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive 115
Connection keep-alive
Referer http://localhost:4242/gwtclient/gwtclient.html
Origin http://localhost:4242
但是我得到了response.getStatusCode()= 0 空洞的回应!
更新2:
我现在感觉很蠢......
问题实际上是SOP ......
我使用的是URL localhost,但在我的代码中我使用的是127.0.0.1!
...该死
答案 0 :(得分:2)
您说您想要使用Async回调,但您从不在代码中使用new AsyncCallback<string>()
。这就是我用gwt应用程序对服务器进行异步调用的方式:(我不使用JSON,但我认为这并不重要)
request object = new request();
object.getMessageXml("test.php", "GET", null, new AsyncCallback<String>() {
@Override
public void onFailure(Throwable caught) {
//error handling
}
@Override
public void onSuccess(String result) {
// do some stuff with the result
}
});
这是请求类:
public void getMessageXml(String file, String type, String requestData, final AsyncCallback<String> callback) {
RootLayoutPanel.get().addStyleName("loading");
final String url = "test/" + file;
RequestBuilder rb;
try {
if(type == "POST") {
rb = new RequestBuilder(RequestBuilder.POST, URL.encode(url));
}
else {
rb = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
}
rb.setHeader("Content-Type", "application/x-javascript; charset:ISO-8859-1");
rb.sendRequest(requestData, new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
if(Response.SC_OK == response.getStatusCode()) {
callback.onSuccess(response.getText());
}
else {
//error
}
RootLayoutPanel.get().removeStyleName("loading");
}
@Override
public void onError(Request request, Throwable exception) {
callback.onFailure(exception);
}
});
}
catch(RequestException rex) {
callback.onFailure(rex);
}
}
[编辑:] 也许你找到了here: