Java HTTP GET响应等待超时 [英] Java HTTP GET response waits until timeout
问题描述
我应该开发一个程序来读取具有指定URL的网页,但问题是我不允许使用任何HTTP库,我只允许使用TCP。
I am supposed to develop a program that reads a web page with the specified URL, but the problem is that I am not allowed to use any HTTP libraries, I am only allowed to use TCP.
以下是读取响应消息的代码:
Below is the code that reads the response message:
private static String readMultiline (BufferedReader inStr) {
String message="";
String line=readLine(inStr);
while (line != null) {
message += line + "\r\n";
line=readLine(inStr);
}
if (message.length() == 0) return null;
return message;
}
private static String readLine (BufferedReader inStr) {
String line = null;
try{
line = inStr.readLine();
} catch (IOException ioe) {
System.out.println("ERROR: Incoming packet could not be read properly.");
return null;
}
return line;
}
问题是标题和网页内容已完全收到,但是while循环仍然等待'next'行,该行不存在。过了一会儿,超时发生,代码继续。我尝试连接的服务器不执行连接:关闭。如何检测文件的结尾?
The problem is that the header and the web page content are completely received, but the while loop still waits for the 'next' line, which does not exist. After a while, timeout occurs and the code continues. The server I am trying to connect to does not do "Connection:close". How can I detect the end of the file?
推荐答案
其他答案已删除,因此我将发布一个。您正在使用读取行信息的IO方法,其中一行被定义为由换行符终止的一组字符。但是不能保证你的TCP数据包以换行结束,所以你需要使用一个更不可知的IO读取来处理它们。
Other answers were deleted so I will post one up. You are using an IO method that read lines of information, with a line being defined as a set of characters terminated by a newline character. But there is no guarantee that your TCP packets are ending in newline, so you need to use a more agnostic IO read to process them.
看看DataInputStream,它有一个名为 readFully
的便捷方法,我认为你会觉得很有用。
Take a look at DataInputStream, it has a convenience method called readFully
that I think you will find quite helpful.
这篇关于Java HTTP GET响应等待超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!