Try block returns String before body code is executed
I'm coding a web application in GWT. I have a class that handles all my http requests and returns the response of the server. This is my current code: (the variable messageXml is defined as a constant)
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 messa开发者_Go百科geXml;
}
catch (RequestException e) {
Window.alert("Could not connect to the server :-(");
return "ERROR";
}
When I call the method httprequest it returns the String first and after that it executes the code in the try body. For example when i do:
request object = new request();
String test = object.httpRequest(file, type, requestData);
Window.alert(test);
It outputs first null (because the String has no content yet) and after that the content of the String. Does anyone know why the method behaves likes this?
Whether messageXml
is defined as a constant or not is not the issue here. Request#sendRequest()
is an asynchronous operation so you cannot make any assumptions about when messageXml
is assigned a value. See GWT's Getting Used to Asynchronous Calls for more details. The correct way to use Request#sendRequest()
is with a callback:
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);
}
}
And to call the method:
object.getMessageXml(someRequestString, new AsyncCallback<String>() {
@Override
public void onFailure(Throwable caught) {
// Handle error.
}
@Override
public void onSuccess(String messageXml) {
// Process response
}
});
精彩评论