乐闻世界logo
搜索文章和话题

cURL 如何设置请求头(Headers)?

3月7日 19:36

在 cURL 中,请求头(Request Headers) 用于传递元数据,如认证信息、内容类型等。正确设置请求头对于 API 调用至关重要。

基本语法

使用 -H--header 参数添加请求头:

bash
curl -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发送 Cookiesession_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

注意事项

  1. 格式要求:请求头必须为 "Name: Value" 格式,冒号后有空格
  2. 大小写:HTTP 头部名称不区分大小写,但建议遵循规范
  3. 特殊字符:如果值包含空格或特殊字符,需要用引号包裹
  4. 重复设置:多次使用 -H 设置同一头部,后者会覆盖前者
标签:cURL