我创建了一个GWT Starter Project我想使用 HTTP Request从另一个站点读取文本文件。
我将此代码放在入口点方法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
}
错误 block 始终执行,并且 response.getStatusCode()
为 0。response.getText()
和 response.getStatusText()
返回空白文本。 GWT HTTP Request 可以用于读取文本文件吗?还是应该使用其他方法?
最佳答案
由于Same Origin Policy,您无法向不同的域发出 HTTP 请求。 .
关于java - 我可以使用 GWT HTTP 请求从网站读取文本文件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18003695/