GET 请求的格式化

Formatting of a GET request

我在 python 的 TCP 客户端中发送数据,我正在学习的教程告诉我发送这个:

"GET / HTTP/1.1\r\nHost: google.com\r\n\r\n"

我已尝试在此处查找有关格式设置的信息,但我对 GET 实际请求的内容或此请求将发回的数据以及回车符的用途感到困惑 returns 和换行符?

如果想在 Python 中编写 low-level HTTP GET,那么您可以创建一个 TCP 套接字,并选择性地使用 header 参数编写 GET 命令,然后读取响应。

HTTP 请求以 Request-line 开头(例如 GET / HTTP/1.1 以终止 CRLF 或“\r\n”)。请求行后跟零个或多个 headers,每个都以 CRLF 结尾。最终的 CRLF 序列标记请求行的结尾和 HTTP 请求的 header 部分,后跟可选消息 body。请求结构在 HTTP 1.1 spec

的第 5 节中定义
import socket

# host and port map to URL http://localhost:8000/
host = "localhost"
port = 8000

try:
    sock = socket.socket()
    sock.connect((host, port))
    sock.sendall("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n".encode())
    # keep reading from socket until no more data in response
    while True:
        response = sock.recv(8096)
        if len(response) == 0:
            break
        print(response)
except Exception as ex:
    print("I/O Error:", ex)

HTTP 响应的第一行是状态行,包括以 \r\n 终止的状态代码,然后是响应 headers。

HTTP/1.1 200 OK\r\n
Content-type: text/plain\r\n
Content-length: 14\r\n
\r\n
This is a test

您需要解析状态行和 headers 以确定如何解码 HTTP 响应的消息 body。

HTTP 响应的详细信息在 HTTP 1.1 Spec 的第 6 部分。

或者,requests 模块以简单的 API 实现 HTTP 规范。

使用请求进行 HTTP GET 的示例 API。

import requests
    
url = 'http://localhost:8000/'
response = requests.get(url)
print("Status code:", response.status_code)
print("Content:", response.text)