📜  Requests-HTTP请求标头

📅  最后修改于: 2020-10-21 08:31:22             🧑  作者: Mango


 

在上一章中,我们已经了解了如何发出请求并获得响应。本章将在URL的标题部分进行更多研究。因此,我们将研究以下内容-

  • 了解请求标头
  • 自定义标题
  • 响应标题

了解Requests标头

在浏览器中点击任何URL,对其进行检查并签入开发者工具的“网络”标签。

您将获得响应头,请求头,有效负载等。

例如,考虑以下URL-

https://jsonplaceholder.typicode.com/users

查看资料

您可以获得标题详细信息,如下所示:

import requests
getdata = requests.get('https://jsonplaceholder.typicode.com/users', 
stream = True)
print(getdata.headers)

输出

E:\prequests>python makeRequest.py
{'Date': 'Sat, 30 Nov 2019 05:15:00 GMT', 'Content-Type': 'application/json; 
charset=utf-8', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 
'Set-Cookie': '__cfduid=d2b84ccf43c40e18b95122b0b49f5cf091575090900; expires=Mon, 30-De
c-19 05:15:00 GMT; path=/; domain=.typicode.com; HttpOnly', 'X-Powered-By': 
'Express', 'Vary': 'Origin, Accept-Encoding', 'Access-Control-Allow-Credentials': 't
rue', 'Cache-Control': 'max-age=14400', 'Pragma': 'no-cache', 'Expires': '-1', '
X-Content-Type-Options': 'nosniff', 'Etag': 'W/"160d-1eMSsxeJRfnVLRBmYJSbCiJZ1qQ
"', 'Content-Encoding': 'gzip', 'Via': '1.1 vegur', 'CF-Cache-Status': 'HIT', 
'Age': '2271', 'Expect-CT': 'max-age=604800, 
report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"', 'Server': 'cloudflare', 'CF-RAY': '53da574f
f99fc331-SIN'}

要读取任何http标头,您可以按照以下步骤操作:

getdata.headers["Content-Encoding"] // gzip

自定义标题

您还可以将标头发送到要调用的URL,如下所示。

import requests
headers = {'x-user': 'test123'}
getdata = requests.get('https://jsonplaceholder.typicode.com/users', 
headers=headers)

传递的标头必须为字符串,bytestring或Unicode格式。根据传递的自定义标头,请求的行为不会改变。

响应标题

当您在浏览器开发人员工具的“网络”标签中检查URL时,响应标题如下所示:

查看源代码

要从请求模块获取标头的详细信息,请使用。 Response.headers如下所示-

import requests
getdata = requests.get('https://jsonplaceholder.typicode.com/users')
print(getdata.headers)

输出

E:\prequests>python makeRequest.py
{'Date': 'Sat, 30 Nov 2019 06:08:10 GMT', 'Content-Type': 'application/json; 
charset=utf-8', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 
'Set-Cookie': '__cfduid=de1158f1a5116f3754c2c353055694e0d1575094090; expires=Mon,
30-Dec-19 06:08:10 GMT; path=/; domain=.typicode.com; HttpOnly', 'X-Powered-By': 
'Express', 'Vary': 'Origin, Accept-Encoding', 'Access-Control-Allow-Credentials': 't
rue', 'Cache-Control': 'max-age=14400', 'Pragma': 'no-cache', 'Expires': '-1', '
X-Content-Type-Options': 'nosniff', 'Etag': 'W/"160d-1eMSsxeJRfnVLRBmYJSbCiJZ1qQ
"', 'Content-Encoding': 'gzip', 'Via': '1.1 vegur', 'CF-Cache-Status': 'HIT', 
'Age': '5461', 'Expect-CT': 'max-age=604800, report-uri="https://report-uri.cloudf
lare.com/cdn-cgi/beacon/expect-ct"', 'Server': 'cloudflare', 'CF-RAY': '53daa52f
3b7ec395-SIN'}

您可以获得所需的任何特定标头,如下所示:

print(getdata.headers["Expect-CT"])

输出

max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/exp
ect-ct

您还可以使用get()方法获取标头详细信息。

print(getdata.headers.get("Expect-CT"))

输出

max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/exp
ect-ct