gpt4 book ai didi

java - 使用 Java 从头开始​​创建服务器 HTTP 客户端

转载 作者:行者123 更新时间:2023-12-01 22:05:18 26 4
gpt4 key购买 nike

我有一个任务

“本作业的目标是练习网络编程并了解应用程序化层协议(protocol)。具体来说,您将实现 HTTP client下载网络程序来自 Internet 上各种 Web 服务器的对象”

我无法使用URL classURLConnection类(class)。所以这让事情变得有点困难。

我知道创建连接的步骤是创建一个 Socket,然后连接到 URL 并使用缓冲 I/O 流与服务器进行通信。

我一直在网上寻找示例,但都使用 URLURLConnection classes .

所以我的思考过程是

  1. 创建套接字 - 将其绑定(bind)到 url + port 80 (我发现80端口是用于http请求的?可能是错误的)

  2. 创建I/O stream到套接字

  3. 握手(我还不知道它到底是如何工作的)

  4. 请求下载
  5. 缓存

我的思维过程正确吗?另外,一旦我得到正确的响应,如何实现从服务器下载图像?

最佳答案

以下是有关超文本传输​​协议(protocol) (HTTP) 中实际发送内容的教程:https://www.jmarshall.com/easy/http/

Sample HTTP Exchange

To retrieve the file at the URL

http://www.somehost.com/path/file.html

first open a socket to the host www.somehost.com, port 80 (use the default port of 80 because none is specified in the URL). Then, send something like the following through the socket:

GET /path/file.html HTTP/1.0
From: someuser@jmarshall.com
User-Agent: HTTPTool/1.0
[blank line here]

The server should respond with something like the following, sent back through the same socket:

HTTP/1.0 200 OK
Date: Fri, 31 Dec 1999 23:59:59 GMT
Content-Type: text/html
Content-Length: 1354

<html>
<body>
<h1>Happy New Millennium!</h1>
(more file contents)
.
.
.
</body>
</html>

After sending the response, the server closes the socket.

关于java - 使用 Java 从头开始​​创建服务器 HTTP 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32912415/

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