gpt4 book ai didi

java - 在 Java 7 中通过 HTTP 检索 XML

转载 作者:数据小太阳 更新时间:2023-10-29 01:57:19 25 4
gpt4 key购买 nike

一些设备(例如 webrelays)返回原始 XML 以响应 HTTPGet 请求。也就是说,回复不包含有效的 HTTP header 。多年来,我一直使用如下代码从此类设备中检索信息:

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,这意味着任何带有无效 header 的 HTTP 响应都会生成 IOException:

1325                respCode = getResponseCode();
1326 if (respCode == -1) {
1327 disconnectInternal();
1328 throw new IOException ("Invalid Http response");
1329 }

在 Java 7 的新世界中,如何从需要 HTTPGet 请求的服务器获取“ headless ”XML?

最佳答案

您总是可以使用“套接字方式”并直接与主机通信 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 引入了这样的“回归”。

干杯,

关于java - 在 Java 7 中通过 HTTP 检索 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19953690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com