gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 10:31:54 25 4
gpt4 key购买 nike

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

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)

我可以远程登录到温度模块:

telnet 192.168.142.55 80
Trying 192.168.142.55...
Connected to 192.168.142.55.
Escape character is '^]'.
GET /state.xml HTTP/1.1

<?xml version='1.0' encoding='utf-8'?>
<datavalues>
<units>F</units>
<sensor1temp>74.0</sensor1temp>
<sensor2temp>67.0</sensor2temp>
<sensor3temp>xx.x</sensor3temp>
<sensor4temp>xx.x</sensor4temp>
<relay1state>0</relay1state>
<relay2state>0</relay2state>
</datavalues>

Connection closed by foreign host.

温度模块似乎没有随回复发送任何 header 。不幸的是,当我查看HttpURLConnection.java时如果没有响应代码,则会抛出 IOException。

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

最佳答案

由于服务器是 not HTTP compliant ,您不应该使用 URL 或 URLConnection。使用普通的 Socket 代替:

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();
}

关于java - 打开 url.openstream 抛出无效的 http 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35042517/

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