我创建了一个GWT 入门项目,我想使用HTTP 请求从另一个站点读取文本文件。
我把这段代码放在入口点方法中onModuleLoad()
:
String url = "http://www.textfiles.com/100/apples.txt";
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
try {
Request myrequest = builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
// Couldn't connect to server (could be
// timeout, SOP violation, etc.)
}
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
Label l = new Label();
l.setText("Response: " + response.getText());
RootPanel.get().add(l);
}
else {
// Handle the error. Can get the status
// text from response.getStatusText()
Label l = new Label();
l.setText("Error. getText() = " + response.getText()
+ " Status text = "
+ response.getStatusText()
+ ". Code: "
+ response.getStatusCode());
RootPanel.get().add(l);
}
}
});
}
catch (RequestException e) {
// Couldn't connect to server
}
错误块总是被执行并且response.getStatusCode()
为 0。response.getText()
并response.getStatusText()
返回空白文本。可以使用 GWT HTTP 请求来读取文本文件,还是应该使用其他方法?