获取原始未解析的HTTP响应

8 投票
1 回答
5068 浏览
提问于 2025-04-17 10:33

有没有简单的方法可以发送一个HTTP请求,并获取原始的、未解析的响应(特别是响应头)?

1 个回答

13

直接使用 socket 模块:

import socket

CRLF = "\r\n"

request = [
    "GET / HTTP/1.1",
    "Host: www.example.com",
    "Connection: Close",
    "",
    "",
]

# Connect to the server
s = socket.socket()
s.connect(('www.example.com', 80))

# Send an HTTP request
s.send(CRLF.join(request))

# Get the response (in several parts, if necessary)
response = ''
buffer = s.recv(4096)
while buffer:
    response += buffer
    buffer = s.recv(4096)

# HTTP headers will be separated from the body by an empty line
header_data, _, body = response.partition(CRLF + CRLF)

print header_data
HTTP/1.0 302 Found
Location: http://www.iana.org/domains/example/
Server: BigIP
Connection: Keep-Alive
Content-Length: 0

撰写回答