HTTP 请求头完全指南

深入理解 HTTP 请求头的各种用法

简介:HTTP 请求头(Request Headers)是客户端发送给服务器的重要信息,包含了请求的各种元数据。掌握请求头的使用对于爬虫开发、API 调用和 Web 开发都至关重要。

一、HTTP 请求头概述

HTTP 请求头是客户端在发送 HTTP 请求时附加的信息,用于告诉服务器关于客户端、请求内容、期望响应等元数据。

请求头分类

  • 通用头部:适用于请求和响应的消息
  • 请求头部:仅用于请求消息
  • 实体头部:描述消息体内容

二、常用请求头详解

2.1 User-Agent

标识客户端类型和版本,服务器根据此信息返回适配的内容。

# Chrome 浏览器 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 # Firefox 浏览器 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:121.0) Gecko/20100101 Firefox/121.0 # Safari 浏览器 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 14_2) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2 Safari/605.1.15 # 移动设备 User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1 # Python requests 默认 User-Agent: python-requests/2.31.0

2.2 Accept

告诉服务器客户端能够处理的内容类型。

# 接受 HTML Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 # 接受 JSON Accept: application/json # 接受所有类型 Accept: */*

质量因子:q=0.9 表示优先级,值为 0-1,越高越优先。如果多个类型有相同 q 值,按顺序优先。

2.3 Accept-Encoding

声明客户端支持的压缩算法。

# 支持多种压缩 Accept-Encoding: gzip, deflate, br # 仅支持 gzip Accept-Encoding: gzip # 不接受压缩 Accept-Encoding: identity

2.4 Accept-Language

声明客户端偏好的语言。

# 中文优先 Accept-Language: zh-CN,zh;q=0.9,en;q=0.8 # 英文优先 Accept-Language: en-US,en;q=0.9 # 多语言支持 Accept-Language: zh-CN,zh-TW,zh-HK;q=0.9,en;q=0.8,ja;q=0.7

2.5 Content-Type

指定请求体的内容类型(主要用于 POST/PUT 请求)。

# JSON 数据 Content-Type: application/json # 表单数据 Content-Type: application/x-www-form-urlencoded # 多部分表单(文件上传) Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW # 纯文本 Content-Type: text/plain; charset=UTF-8 # XML Content-Type: application/xml

2.6 Authorization

包含认证凭据,用于访问受保护的资源。

# Basic 认证 Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l # Bearer Token (OAuth 2.0) Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... # API Key Authorization: Api-Key your-api-key-here # 自定义认证 Authorization: Custom auth-token-here

2.7 Cookie

携带客户端存储的 Cookie 信息,用于会话管理。

# 基本格式 Cookie: name1=value1; name2=value2 # 实际示例 Cookie: session_id=abc123; user_token=xyz789; theme=dark; lang=zh-CN # 带过期和域信息 Cookie: session=def456; Expires=Wed, 21 Oct 2026 07:28:00 GMT; Domain=example.com

2.8 Referer

指示请求来源 URL,用于防盗链和统计分析。

# 从搜索引擎跳转 Referer: https://www.google.com/search?q=test # 从网站内部页面跳转 Referer: https://example.com/products # 不发送 Referer Referer:

2.9 Origin

指示请求的源,用于 CORS(跨域资源共享)验证。

# 标准 CORS 请求 Origin: https://example.com # 同源请求可以省略

三、特定用途的请求头

3.1 Range

请求资源的部分内容,常用于断点续传。

# 请求前 500 字节 Range: bytes=0-499 # 请求 500-999 字节 Range: bytes=500-999 # 请求从 500 字节开始到结尾 Range: bytes=500- # 请求最后 500 字节 Range: bytes=-500 # 请求多个范围 Range: bytes=0-500,1000-1500

3.2 If-Modified-Since / If-None-Match

条件请求,用于缓存验证。

# 基于 Last-Modified If-Modified-Since: Wed, 21 Oct 2026 07:28:00 GMT # 基于 ETag If-None-Match: "33a64df551425fcc55e4d42a148795d9f25f89d4" # 如果资源未修改,服务器返回 304 Not Modified

3.3 X-Requested-With

标识 AJAX 请求。

# 标识为 AJAX 请求 X-Requested-With: XMLHttpRequest # jQuery 自动添加此头部

四、安全相关的请求头

4.1 Host

指定请求的主机名(虚拟主机必需)。

Host: example.com Host: www.example.com:8080

4.2 Connection

控制连接行为。

# 保持连接 Connection: keep-alive # 关闭连接 Connection: close

4.3 DNT (Do Not Track)

告知服务器不希望被跟踪。

DNT: 1 # 不希望被跟踪 DNT: 0 # 允许被跟踪

4.4 Upgrade-Insecure-Requests

请求升级到 HTTPS。

Upgrade-Insecure-Requests: 1

五、Python 中使用请求头

import requests # 设置基本请求头 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', 'Accept': 'application/json', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Accept-Encoding': 'gzip, deflate', } response = requests.get('https://api.example.com/data', headers=headers) # POST 请求设置 Content-Type headers['Content-Type'] = 'application/json' data = {'name': '张三', 'age': 25} response = requests.post('https://api.example.com/users', json=data, headers=headers) # 携带 Cookie headers['Cookie'] = 'session_id=abc123; user_token=xyz789' response = requests.get('https://api.example.com/profile', headers=headers) # 设置认证 headers['Authorization'] = 'Bearer your-token-here' response = requests.get('https://api.example.com/protected', headers=headers) # 使用 Session 自动管理 Cookie 和请求头 session = requests.Session() session.headers.update({ 'User-Agent': 'Mozilla/5.0 ...', 'Accept': 'application/json', }) # 登录后 Session 会自动保存 Cookie session.post('https://api.example.com/login', json={'user': 'admin', 'pass': '123456'}) # 后续请求自动携带 Cookie 和设置的请求头 response = session.get('https://api.example.com/protected')

六、爬虫开发中的请求头技巧

import random # User-Agent 池 USER_AGENTS = [ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:121.0) Gecko/20100101 Firefox/121.0', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 14_2) AppleWebKit/605.1.15 Safari/605.1.15', ] def random_user_agent(): return random.choice(USER_AGENTS) # 完整的浏览器请求头模板 def get_browser_headers(): return { 'User-Agent': random_user_agent(), 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8', 'Accept-Encoding': 'gzip, deflate, br', 'DNT': '1', 'Connection': 'keep-alive', 'Upgrade-Insecure-Requests': '1', 'Sec-Fetch-Dest': 'document', 'Sec-Fetch-Mode': 'navigate', 'Sec-Fetch-Site': 'none', 'Cache-Control': 'max-age=0', } # 获取浏览器中的真实请求头 # 使用 EasySpider 工具从浏览器开发者工具复制 Curl 命令 # 然后提取其中的请求头信息

七、常见问题解决

7.1 403 Forbidden

可能原因:缺少必要的请求头、User-Agent 被识别、Referer 检测。

# 解决方案 headers = { 'User-Agent': 'Mozilla/5.0 ...', 'Referer': 'https://example.com', # 添加 Referer 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', } response = requests.get(url, headers=headers)

7.2 401 Unauthorized

可能原因:缺少认证信息或认证信息错误。

# 解决方案 headers = { 'Authorization': 'Bearer your-token-here', } response = requests.get(url, headers=headers)

调试技巧:使用浏览器开发者工具查看完整的请求头,与你的爬虫请求头进行对比,找出差异。

总结

掌握 HTTP 请求头的使用对于开发和爬虫都至关重要。通过本文的学习,你应该能够:

  • 理解常用请求头的作用
  • 正确设置请求头参数
  • 解决常见的请求头相关问题
  • 使用 EasySpider 工具快速获取真实请求头