【问题标题】:Getting a raw, unparsed HTTP response获取原始的、未解析的 HTTP 响应
【发布时间】:2012-02-13 15:46:33
【问题描述】:

是否有任何直接的方法可以发出 HTTP 请求并获取原始的、未解析的响应(特别是标头)?

【问题讨论】:

  • 您究竟希望用它做什么,而用更用户友好的方式接收数据却无法做到?
  • 我想看看服务器在响应中是否使用\n而不是\r\n

标签: python http-headers http-request


【解决方案1】:

直接使用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

【讨论】:

  • 哇,感谢您提供完整的解决方案!如果您需要使用 HTTPS,这会变得更加复杂吗?
  • 谢谢,Jeremy -- 我刚刚再次登录以添加响应拆分,你打败了我 :)
  • @Acorn:如果你想以这种方式使用 SSL,你需要导入 ssl 模块,并使用 SSLSocket 而不是常规套接字。我自己没有使用过,所以可能有其他差异。听起来像是另一个 SO 问题的好话题,不过:)
猜你喜欢
  • 1970-01-01
  • 2020-10-04
  • 1970-01-01
  • 2011-10-10
  • 1970-01-01
  • 2022-01-18
  • 2016-01-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多