一些设备(例如 webrelays)返回原始 XML 以响应 HTTPGet 请求。也就是说,回复不包含有效的 HTTP 标头。多年来,我使用以下代码从此类设备中检索信息:
private InputStream doRawGET(String url) throws MalformedURLException, IOException
{
try
{
URL url = new URL(url);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
return con.getInputStream();
}
catch (SocketTimeoutException ex)
{
throw new IOException("Timeout attempting to contact Web Relay at " + url);
}
}
在 openJdk 7 中,以下行已添加到 sun.net.www.protocol.http.HttpURLConnection,这意味着任何带有无效标头的 HTTP 响应都会生成 IOException:
1325 respCode = getResponseCode();
1326 if (respCode == -1) {
1327 disconnectInternal();
1328 throw new IOException ("Invalid Http response");
1329 }
在 Java 7 的新世界中,如何从需要 HTTPGet 请求的服务器获取“无头”XML?