在 cURL 中,请求头(Request Headers) 用于传递元数据,如认证信息、内容类型等。正确设置请求头对于 API 调用至关重要。
基本语法
使用 -H 或 --header 参数添加请求头:
bashcurl -H "Header-Name: Header-Value" URL
常用请求头示例
bash# 设置 Content-Type curl -H "Content-Type: application/json" \ https://api.example.com/users # 设置 Authorization(Bearer Token) curl -H "Authorization: Bearer your_token_here" \ https://api.example.com/protected # 设置 User-Agent curl -H "User-Agent: MyApp/1.0" \ https://api.example.com/data # 设置 Accept(期望的响应格式) curl -H "Accept: application/json" \ https://api.example.com/users # 设置多个请求头 curl -H "Content-Type: application/json" \ -H "Authorization: Bearer token123" \ -H "Accept: application/json" \ -H "X-Custom-Header: custom-value" \ https://api.example.com/users
常见请求头类型
| 请求头 | 用途 | 示例 |
|---|---|---|
| Content-Type | 指定请求体格式 | application/json, application/x-www-form-urlencoded |
| Authorization | 身份认证 | Bearer token, Basic auth |
| Accept | 期望的响应格式 | application/json, text/html |
| User-Agent | 客户端标识 | Mozilla/5.0, MyApp/1.0 |
| Cookie | 发送 Cookie | session_id=abc123 |
| Cache-Control | 缓存控制 | no-cache |
特殊用法
bash# 发送 Cookie curl -H "Cookie: session_id=abc123; user_id=456" \ https://api.example.com/profile # 跨域请求 curl -H "Origin: https://example.com" \ -H "Access-Control-Request-Method: POST" \ https://api.example.com/data # 压缩请求 curl -H "Content-Encoding: gzip" \ --data-binary @compressed.gz \ https://api.example.com/upload # 从文件读取请求头 curl -H @headers.txt https://api.example.com/users
注意事项
- 格式要求:请求头必须为 "Name: Value" 格式,冒号后有空格
- 大小写:HTTP 头部名称不区分大小写,但建议遵循规范
- 特殊字符:如果值包含空格或特殊字符,需要用引号包裹
- 重复设置:多次使用
-H设置同一头部,后者会覆盖前者