Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java7中通过HTTP检索XML_Java_Xml_Http_Java 7 - Fatal编程技术网

在Java7中通过HTTP检索XML

在Java7中通过HTTP检索XML,java,xml,http,java-7,Java,Xml,Http,Java 7,一些设备(如WebRelay)返回原始XML以响应HTTPGet请求。也就是说,回复不包含有效的HTTP头。多年来,我一直使用以下代码从此类设备检索信息: private InputStream doRawGET(String url) throws MalformedURLException, IOException { try { URL url = new URL(url); HttpURLConnection con = (HttpURLC

一些设备(如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请求的服务器获取“headless”XML?

您始终可以通过“socket方式”实现,并直接与主机进行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引入了这样的“回归”


干杯,

这是一个非常简单的解决方案。非常感谢。在我的平台(Linux)上,我不得不修改线路终端。因此,我使用了out.print(“GET”+relativeURL+“HTTP/1.1\r\n\r\n”);不过,有文档记录了使用HTTP1.1的不错的捕获,它允许响应在标题中提供一个状态行。只有在HTTP1.0下,这才是有效的HTTP响应。mabi:甚至在1.0下也不是。在0.9,是的。