[英]DocumentBuilder.parse seems to randomly skip the beginning of returned XML InputStream from a HTTP request
我有以下代码来发送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:序言中不允许内容。
org.xml.sax.SAXParseException; lineNumber:1; columnNumber:1; 序言中不能有内容。
在com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(未知来源)
在com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(未知来源)
在javax.xml.parsers.DocumentBuilder.parse(未知来源)
...
如果我尝试使用Chrome浏览器访问URL,则无论我重新加载多少次,每次都会收到有效的XML响应。 此外,当我在笔记本电脑上运行完全相同的代码时,似乎没有出现相同的问题。
稍作修改后,我尝试将InputStream
s直接打印为字符串(使用此链接中的方法4),而不是解析它们,并且我注意到有时响应实际上没有预期的XML标头( <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
),但其他时候确实如此。
我的猜测是我在流中做错了,但我不知道该怎么办。
我发现了问题。 该站点似乎有时返回JSON响应而不是XML,这导致解析器异常。 我在runQuery
添加了以下行:
connection.setRequestProperty("Accept", "application/xml");
现在,我可以成功运行代码而不会出现错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.