某些设备(例如webrelay)会返回原始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?
答案 0 :(得分:4)
您可以随时使用“套接字方式”并将HTTP直接与主机进行对话:
private InputStream doRawGET( String url )
{
Socket s = new Socket( new URL( url ).getHost() , 80 );
PrintWriter out = new PrintWriter( s.getOutputStream() , true );
out.println( "GET " + new URL( url ).getPath() + " HTTP/1.0" );
out.println(); // extra CR necessary sometimes.
return s.getInputStream():
}
不完全优雅,但它会起作用。奇怪的是,JRE7引入了这样的“回归”。
干杯,