Java HTTP GET响应等待超时

编程入门 行业动态 更新时间:2024-10-24 18:19:18
本文介绍了Java HTTP GET响应等待超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我应该开发一个程序来读取具有指定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响应等待超时

本文发布于:2023-08-07 18:16:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1320833.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Java   HTTP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!