打开url.openstream会抛出无效的http响应

时间:2016-01-27 16:16:08

标签: java http url

我正在尝试从温度模块读取文件,当我在url上调用openStream()时,我收到一条带有“无效的Http响应”消息的IOExeption

http://myip:5601

我可以telnet到温度模块:

SEVERE: null
java.io.IOException: Invalid Http response
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1555)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)
at java.net.URL.openStream(URL.java:1038)
at thermometerpoller.Poller.poll(Poller.java:38)

似乎温度模块没有发送带回复的任何标题。 不幸的是,当我查看HttpURLConnection.java是否没有响应代码时,它会抛出IOException。

我的问题是,有没有办法通过库或其他方法获取文件内容而不关心响应代码是什么?

1 个答案:

答案 0 :(得分:1)

由于服务器为not HTTP compliant,因此不应使用URL或URLConnection。请改用普通插座:

Document doc;

final Socket connection = new Socket("192.168.142.55", 80);

try (final OutputStream out = connection.getOutputStream();
     InputStream in = connection.getInputStream()) {

    Callable<Void> requestSender = new Callable<Void>() {
        @Override
        public Void call()
        throws IOException {
            String request = "GET /state.xml HTTP/1.1\n\n";
            out.write(request.getBytes(StandardCharsets.US_ASCII));
            return null;
        }
    };
    ExecutorService background = Executors.newSingleThreadExecutor();
    Future<?> request = background.submit(requestSender);

    doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in);

    request.get();
    background.shutdown();
}