gpt4 book ai didi

python - 来自请求 Python 库的 HTTP 请求中缺少主机 header

转载 作者:太空宇宙 更新时间:2023-11-04 11:12:51 25 4
gpt4 key购买 nike

HTTP/1.1 mandatory Host header field 在哪里?在 requests Python 库生成的 HTTP 请求消息中?

import requests

response = requests.get("https://www.google.com/")
print(response.request.headers)

输出:

{'User-Agent': 'python-requests/2.22.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}

最佳答案

默认情况下,requests 不会将 HOST header 添加到请求中。如果未明确添加,则将决定委托(delegate)给基础 http 模块。

请参阅 http/client.py 的这一部分:

(如果 'Host' header 在 requests.get 中明确提供,则 skip_hostTrue)

    if self._http_vsn == 11:
# Issue some standard headers for better HTTP/1.1 compliance

if not skip_host:
# this header is issued *only* for HTTP/1.1
# connections. more specifically, this means it is
# only issued when the client uses the new
# HTTPConnection() class. backwards-compat clients
# will be using HTTP/1.0 and those clients may be
# issuing this header themselves. we should NOT issue
# it twice; some web servers (such as Apache) barf
# when they see two Host: headers

# If we need a non-standard port,include it in the
# header. If the request is going through a proxy,
# but the host of the actual URL, not the host of the
# proxy.

netloc = ''
if url.startswith('http'):
nil, netloc, nil, nil, nil = urlsplit(url)

if netloc:
try:
netloc_enc = netloc.encode("ascii")
except UnicodeEncodeError:
netloc_enc = netloc.encode("idna")
self.putheader('Host', netloc_enc)
else:
if self._tunnel_host:
host = self._tunnel_host
port = self._tunnel_port
else:
host = self.host
port = self.port

try:
host_enc = host.encode("ascii")
except UnicodeEncodeError:
host_enc = host.encode("idna")

# As per RFC 273, IPv6 address should be wrapped with []
# when used as Host header

if host.find(':') >= 0:
host_enc = b'[' + host_enc + b']'

if port == self.default_port:
self.putheader('Host', host_enc)
else:
host_enc = host_enc.decode("ascii")
self.putheader('Host', "%s:%s" % (host_enc, port))

因此,在检查 requests 发送到服务器的 header 时,我们看不到 'Host' header 。

如果我们向 http://httpbin/get 发送请求并打印响应,我们可以看到确实发送了 Host header 。

import requests

response = requests.get("http://httpbin.org/get")
print('Response from httpbin/get')
print(response.json())
print()
print('response.request.headers')
print(response.request.headers)

输出

Response from httpbin/get
{'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate',
'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.20.0'},
'origin': 'XXXXXX', 'url': 'https://httpbin.org/get'}

response.request.headers
{'User-Agent': 'python-requests/2.20.0', 'Accept-Encoding': 'gzip, deflate',
'Accept': '*/*', 'Connection': 'keep-alive'}

关于python - 来自请求 Python 库的 HTTP 请求中缺少主机 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57770557/

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