获取原始的,未解析的HTTP响应

Aco*_*orn 8 python http-headers http-request

是否有任何直接的方法来发出HTTP请求并获得原始的,未解析的响应(特别是标题)?

Ian*_*and 13

直接使用套接字模块:

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
Run Code Online (Sandbox Code Playgroud)
HTTP/1.0 302 Found
Location: http://www.iana.org/domains/example/
Server: BigIP
Connection: Keep-Alive
Content-Length: 0
Run Code Online (Sandbox Code Playgroud)

  • @Acorn:如果你想以这种方式做SSL,你需要使用ssl模块,并使用SSLSocket而不是常规套接字.我自己没有使用它,所以可能还有其他差异.听起来像另一个SO问题的好主题,但:) (3认同)