如何使用python获取请求原始请求头的全部内容

问题描述 投票:0回答:1

比如

POST /service/rapture/session HTTP/1.1
Host: 192.168.136.155:8081
Content-Length: 39
X-Requested-With: XMLHttpRequest
X-Nexus-UI: true
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.5672.127 Safari/537.36
NX-ANTI-CSRF-TOKEN: 0.74934606792014381.1.691978768.1713947526; _gid=GA1.1.1983366476.1713947526; metabase.TIMEOUT=aliv
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Accept: */*

我怎样才能得到这个标题?

我使用了requests方法,但是它返回的请求头内容很小。

python python-requests header
1个回答
0
投票

requests
库对Python的网络请求API进行了多层封装,仅提供高层接口。因此,用
requests
不太可能实现这一点。

这是从低级 API 获取原始标头的示例:

import http.client
host = "docs.python.org"
conn = http.client.HTTPSConnection(host)
conn.request("GET", "/3/", headers={"Host": host})
response = conn.getresponse()
print(list(response.headers.raw_items()))

上面的代码生成如下输出:

[('Connection', 'keep-alive'),
 ('Content-Length', '19561'),
 ('server', 'nginx'),
 ('content-type', 'text/html'),
 ('last-modified', 'Wed, 24 Apr 2024 21:00:51 GMT'),
 ('etag', '"66297303-4c69"'),
 ('x-clacks-overhead', 'GNU Terry Pratchett'),
 ('strict-transport-security', 'max-age=315360000; includeSubDomains; preload'),
 ('Via', '1.1 varnish, 1.1 varnish'),
 ('Accept-Ranges', 'bytes'),
 ('Date', 'Thu, 25 Apr 2024 02:48:30 GMT'),
 ('Age', '20831'),
 ('X-Served-By', 'cache-lga21956-LGA, cache-tyo11964-TYO'),
 ('X-Cache', 'HIT, HIT'),
 ('X-Cache-Hits', '19, 1'),
 ('X-Timer', 'S1714013311.518366,VS0,VE1'),
 ('Vary', 'Accept-Encoding')]

如果不需要调用低级API,您可以从

requests
的响应头中手动构造此结果。

© www.soinside.com 2019 - 2024. All rights reserved.