我可以使用GWT HTTP请求从网站读取文本文件吗?

时间:2013-08-01 20:15:14

标签: java gwt httprequest

我创建了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
}

始终执行错误块,response.getStatusCode()为0. response.getText()response.getStatusText()返回空白文本。可以使用GWT HTTP Request来读取文本文件,还是应该使用其他方法?

1 个答案:

答案 0 :(得分:2)

由于Same Origin Policy

,您无法向不同的域发出HTTP请求