Skip to content

Requests - HTTP 请求头

使用 Requests 理解和使用 HTTP 头部

Section titled “使用 Requests 理解和使用 HTTP 头部”

HTTP 头部(headers)是 HTTP 请求和响应的关键组成部分,携带着关于消息的元数据,例如内容类型、身份验证令牌、缓存指令等。本章探讨如何使用 requests 库检查响应头部和发送自定义请求头部。

  • 检查响应头部
  • 发送自定义请求头部
  • 头部的常见用例

当你发起请求时,服务器会返回一个包含头部的响应。这些头部提供了关于响应本身的宝贵信息。requests 库通过 Response 对象的 headers 属性使这些头部易于访问。

response.headers 属性是一个类似字典的对象(具体来说,是一个 CaseInsensitiveDict),它允许你访问头部值。头部名称不区分大小写。

import requests
response = requests.get('https://jsonplaceholder.typicode.com/todos/1')
print("All Response Headers:")
for key, value in response.headers.items():
print(f"{key}: {value}")
All Response Headers:
Date: Mon, 01 Jul 2024 10:00:00 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 83
Connection: keep-alive
Cache-Control: public, max-age=14400
Etag: W/"53-hf75nVaR4L/XeNTPTY/042RfiEY"
...

你可以通过名称访问特定的头部值。使用 .get() 方法更安全,因为它在头部不存在时返回 None,从而避免 KeyError 异常。

import requests
response = requests.get('https://jsonplaceholder.typicode.com/todos/1')
content_type = response.headers.get('Content-Type')
print(f"Content-Type: {content_type}")
# 使用 get() 访问不存在的头部
non_existent_header = response.headers.get('X-Custom-Header')
print(f"X-Custom-Header: {non_existent_header}")
# 使用字典风格访问(不区分大小写)
server_header = response.headers['server'] # 假设 'server' 头部存在
print(f"Server: {server_header}")
Content-Type: application/json; charset=utf-8
X-Custom-Header: None
Server: cloudflare

有时,你需要随请求发送自定义头部。这可能是为了身份验证(例如,API 密钥)、指定期望的响应内容类型(Accept 头部),或提供其他元数据。你可以将一个头部字典传递给任何请求方法(get、post 等)的 headers 参数。

import requests
url = 'https://httpbin.org/headers' # 这个接口会回显请求头部
custom_headers = {
'X-API-Key': 'your_secret_api_key_here',
'User-Agent': 'MyAwesomeApp/1.0',
'Accept': 'application/json'
}
response = requests.get(url, headers=custom_headers)
print(f"Status Code: {response.status_code}")
# 来自 httpbin.org/headers 的响应将包含我们发送的头部。
print("Echoed Headers from Server:")
print(response.json()['headers'])
Status Code: 200
Echoed Headers from Server:
{
"Accept": "application/json",
"Accept-Encoding": "gzip, deflate, br, zstd",
"Host": "httpbin.org",
"User-Agent": "MyAwesomeApp/1.0",
"X-Amzn-Trace-Id": "Root=...",
"X-Api-Key": "your_secret_api_key_here"
}

请注意,requests 会默认添加一些头部(例如 Host、Accept-Encoding,以及在未被覆盖时的默认 User-Agent)。你自定义的头部将被添加或覆盖这些默认值。

  • Authorization:发送凭据,如 API 密钥或 bearer token(例如,Authorization: Bearer <token>)。
  • Content-Type:(用于 POST/PUT 等请求)指定请求体的媒体类型(例如,application/json、application/x-www-form-urlencoded)。当使用 data 或 json 参数时,requests 通常会自动设置此头部。
  • Accept:告知服务器客户端可以理解的响应内容类型(例如,Accept: application/json)。
  • User-Agent:标识发出请求的客户端软件。为你的应用程序设置一个有描述性的 User-Agent 是一个好习惯。
  • If-None-Match / If-Modified-Since:用于条件请求,通过避免重新下载未更改的数据(与缓存和 ETags 相关)来提高应用程序的效率。

有效理解和利用 HTTP 头部是健壮且高效地与 Web 服务和 API 交互的关键。

有关 HTTP 头部及其含义的完整列表,请查阅 MDN Web Docs:https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers