我有一个迭代方法,它将对url进行100次调用,然后解析XML响应并在每次调用后保留数据。
为了实现这一点,我一直在尝试使用HttpURLConnection来获取响应,将其转换为字符串,然后是文档,以便我可以处理它并使用SAX解析我想要的标签/信息。
但是,这种方法有时只能起作用,中间我得到以下异常:
org.xml.sax.SAXParseException: Content is not allowed in prolog.
问题似乎是XML String并不总能正常返回。而不是使用中间的数据获取普通的XML标记,如:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> </xml>
我得到这样的东西:
{"created":"2019-03-18T13:19:41.484Z","count":3654,"offset":500 ....
该字符串包含我需要的数据,但由于某种原因,似乎响应并不总是以我需要的形式返回它。我已经确认这是一个间歇性问题,这意味着我已经达到了同样的要求,有时会收到所需的响应,而其他人则收到了不良反应。
发出请求的方法
URL url = new URL("Some URL");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
int responseCode = connection.getResponseCode();
if (responseCode != 200) {
log.error("Received an invalid response: " + responseCode);
return;
}
parseXml(convertResponseToXmlString(connection));
connection.disconnect();
将响应转换为String的方法
private String convertResponseToXmlString(final HttpURLConnection connection) throws IOException
{
String inputLine;
BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer content = new StringBuffer();
while ((inputLine = input.readLine()) != null)
{
content.append(inputLine);
}
input.close();
return content.toString().trim();
}
connection.setRequestProperty("Content-Type", "application/xml");
应该帮助:)或者尝试:
connection.setRequestProperty("Accept", "application/xml");