我在GWT编写Web应用程序。我有一个类来处理我的所有http请求并返回服务器的响应。 这是我当前的代码:(变量messageXml被定义为常量)
try {
Request request = builder.sendRequest(requestData, new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
if(200 == response.getStatusCode()) {
messageXml = response.getText();
}
else {
Window.alert("There was an error (1) :-(");
messageXml = "ERROR";
}
}
@Override
public void onError(Request request, Throwable exception) {
Window.alert("There was an error (2) :-(");
messageXml = "ERROR";
}
});
Window.alert(messageXml);
return messageXml;
}
catch (RequestException e) {
Window.alert("Could not connect to the server :-(");
return "ERROR";
}
当我调用方法httprequest时,它首先返回String,然后执行try主体中的代码。 例如,当我这样做时:
request object = new request();
String test = object.httpRequest(file, type, requestData);
Window.alert(test);
它输出第一个null(因为String还没有内容),然后输出String的内容。有谁知道为什么这个方法表现得像这样?
答案 0 :(得分:3)
messageXml
是否定义为常量不是问题所在。 Request#sendRequest()
是一个异步操作,因此您无法对messageXml
何时赋值进行任何假设。有关详细信息,请参阅GWT的Getting Used to Asynchronous Calls。使用Request#sendRequest()
的正确方法是使用回调:
public void getMessageXml(String requestData,
final AsyncCallback<String> callback) {
try {
// Modify for your application.
RequestBuilder rb = new RequestBuilder(Method.GET,
"http://www.mycompany.com/getMessageXml");
rb.sendRequest(requestData, new RequestCallback() {
@Override
public void onError(Request request, Throwable caught) {
callback.onFailure(caught);
}
@Override
public void onResponseReceived(Request request, Response response) {
if (Response.SC_OK == response.getStatusCode()) {
callback.onSuccess(response.getText());
} else {
// Use a correctly typed exception here.
callback.onFailure(...);
}
}
});
} catch (RequestException rex) {
callback.onFailure(rex);
}
}
并调用方法:
object.getMessageXml(someRequestString, new AsyncCallback<String>() {
@Override
public void onFailure(Throwable caught) {
// Handle error.
}
@Override
public void onSuccess(String messageXml) {
// Process response
}
});