GWT在服务器上检索XML数据

时间:2015-04-10 11:59:55

标签: java xml gwt

我尝试从外部服务器检索XML数据并在我的GWT应用程序上显示信息。

问题是我没有成功显示xml信息。

我的Java代码:

protected void retrieveXmlDataTop(final VerticalPanel c) {

    url = "http://www.myapifilms.com/imdb/top?format=XML&start=1&end=25&data=S";

    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET,URL.encode(url));

    try
    {
        builder.sendRequest(null, new RequestCallback() {

            @Override
            public void onError(Request request, Throwable exception) {
                // Couldn't connect to server (could be timeout, SOP
                // violation, etc.)
                Window.alert("Couldn't retrieve XML");

            }

            @Override
            public void onResponseReceived(Request request, Response response) {

                if (200 == response.getStatusCode())
                {
                    // Process the response in response.getText()
                    parseMessage(c , response.getText());
                }
                else
                {
                    // Handle the error. Can get the status text from
                    // response.getStatusText()
                    //Window.alert("Error: " + response.getStatusText());
                    Label error = new Label("Error");
                    c.add(error);
                }
            }


        });
    }
    catch (RequestException e)
    {
        // Couldn't connect to server
        Window.alert("Couldn't connect to server to retrieve the XML: \n");
    }
}

private void parseMessage(final VerticalPanel c, String messageXml)
{
    try
    {
        // parse the XML document into a DOM
        Document messageDom = XMLParser.parse(messageXml);

        String tag1Value = messageDom.getElementsByTagName("ranking").item(0)
                .getFirstChild().getNodeValue();
        String tag2Value = messageDom.getElementsByTagName("title").item(0)
                .getFirstChild().getNodeValue();

        //Window.alert("Ranking Value: " + tag1Value + "\n" + "Title Value: " + tag2Value);
        Label result = new Label("Ranking Value: " + tag1Value + "\n" + "Title Value: " + tag2Value);
        c.add(result);

    }
    catch (DOMException e)
    {
        Window.alert("Could not parse XML document.");
    }
}

我的xml页面:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<movies>
    <movie>
        <idIMDB>tt0111161</idIMDB>
        <ranking>1</ranking>
        <rating>9.2</rating>
        <title>The Shawshank Redemption</title>
        <urlPoster>http://ia.media-imdb.com/images/M/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE@._V1_SX34_CR0,0,34,50_AL_.jpg</urlPoster>
        <year>1994</year>
    </movie>
</movies>

我总是收到消息“错误”。

1 个答案:

答案 0 :(得分:0)

由于same-origin-policy,你无法得到答案。 (状态码0表示提示)

如果您打开浏览器的开发工具,您可能会看到请求和响应,并且可能是有关请求安全问题的警告。

如果您想从服务器获得答案,您的前端必须从与API或API服务器相同的来源提供,并且浏览器必须符合CORS