5月28日 02:37

How to set request headers in cURL?

In cURL, Request Headers are used to pass metadata such as authentication information and content types. Properly setting request headers is crucial for API calls.

Basic Syntax

Use the -H or --header parameter to add request headers:

bash
curl -H "Header-Name: Header-Value" URL

Common Request Header Examples

bash
# Set Content-Type curl -H "Content-Type: application/json" \ https://api.example.com/users # Set Authorization (Bearer Token) curl -H "Authorization: Bearer your_token_here" \ https://api.example.com/protected # Set User-Agent curl -H "User-Agent: MyApp/1.0" \ https://api.example.com/data # Set Accept (expected response format) curl -H "Accept: application/json" \ https://api.example.com/users # Set multiple headers 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

Common Header Types

HeaderPurposeExample
Content-TypeSpecify request body formatapplication/json, application/x-www-form-urlencoded
AuthorizationAuthenticationBearer token, Basic auth
AcceptExpected response formatapplication/json, text/html
User-AgentClient identificationMozilla/5.0, MyApp/1.0
CookieSend cookiessession_id=abc123
Cache-ControlCache controlno-cache

Special Use Cases

bash
# Send Cookie curl -H "Cookie: session_id=abc123; user_id=456" \ https://api.example.com/profile # CORS request curl -H "Origin: https://example.com" \ -H "Access-Control-Request-Method: POST" \ https://api.example.com/data # Compressed request curl -H "Content-Encoding: gzip" \ --data-binary @compressed.gz \ https://api.example.com/upload # Read headers from file curl -H @headers.txt https://api.example.com/users

Important Notes

  1. Format: Headers must be in "Name: Value" format with a space after the colon
  2. Case Sensitivity: HTTP header names are case-insensitive, but follow conventions
  3. Special Characters: Wrap values with quotes if they contain spaces or special characters
  4. Duplicate Headers: Using -H multiple times for the same header will override previous values
标签:cURL