【问题标题】:DocumentBuilder.parse seems to randomly skip the beginning of returned XML InputStream from a HTTP requestDocumentBuilder.parse 似乎从 HTTP 请求中随机跳过返回的 XML InputStream 的开头
【发布时间】:2018-01-30 22:05:14
【问题描述】:

我有以下代码来发送 HTTP 请求、接收响应(以 XML 的形式)并解析它:

public Document getDocumentElementFromDatabase() {
    // this URL is actually built dynamically from a query, but for this example I just use one of the possible resulting URLs
    String url = "http://musicbrainz.org/ws/2/recording?query=%22Thunderstruck%22+AND+artistname%3A%222Cellos%22";

    try {
        // sleep between successive requests to avoid flooding the server
        Thread.sleep(1000);
        HttpURLConnection connection = runQuery(url);
        InputStream stream = connection.getInputStream();
        if (stream != null) {
            BufferedInputStream buff = new BufferedInputStream(stream);
            return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(buff);
        }
    }

    // I've grouped exception handling for this example
    catch (ParserConfigurationException | InterruptedException | SAXException | IOException e) {
        e.printStackTrace();
    }

    finally {
        if (connection != null) connection.disconnect();
    }

    return null;
}

private void runQuery(String url) throws MalformedURLException, IOException {
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setRequestProperty("User-Agent", "MyAppName/1.0 ( myemail@email.email )");
    return connection;
}

此代码被多次调用,有时我收到以下错误:

[致命错误] :1:1: prolog 中不允许内容。

org.xml.sax.SAXParseException;行号:1;列号:1;序言中不允许有内容。

在 com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(未知来源)

在 com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(未知来源)

在 javax.xml.parsers.DocumentBuilder.parse(Unknown Source)

...

如果我尝试访问 Chrome 中的 URL,我每次都会收到有效的 XML 响应,无论我重新加载多少次。更重要的是,当我在笔记本电脑上运行完全相同的代码时,似乎没有出现同样的问题。

经过一番修改,我尝试将InputStreams 直接打印为字符串(使用this link 中的方法4),而不是解析它们,我注意到有时响应实际上没有预期的XML标头 (<?xml version="1.0" encoding="UTF-8" standalone="yes"?>),但其他时候确实如此。

我的猜测是我在流中做错了什么,但我不知道是什么。

【问题讨论】:

  • 您每 1 秒拨打一次电话,因此使用浏览器进行测试不是一个好方法。尝试每 10 秒或更长时间读取一次,看看是否有更少的错误。
  • 我已经尝试使用 10 秒延迟,但仍然出现错误。

标签: java xml parsing inputstream


【解决方案1】:

我发现了问题。该站点有时似乎返回 JSON 响应而不是 XML,这导致解析器崩溃。我在runQuery 中添加了以下行:

connection.setRequestProperty("Accept", "application/xml");

我现在可以成功运行代码而不会出错。

【讨论】:

    猜你喜欢
    • 2011-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 2018-05-30
    相关资源
    最近更新 更多