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:
bashcurl -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
| Header | Purpose | Example |
|---|---|---|
| Content-Type | Specify request body format | application/json, application/x-www-form-urlencoded |
| Authorization | Authentication | Bearer token, Basic auth |
| Accept | Expected response format | application/json, text/html |
| User-Agent | Client identification | Mozilla/5.0, MyApp/1.0 |
| Cookie | Send cookies | session_id=abc123 |
| Cache-Control | Cache control | no-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
- Format: Headers must be in "Name: Value" format with a space after the colon
- Case Sensitivity: HTTP header names are case-insensitive, but follow conventions
- Special Characters: Wrap values with quotes if they contain spaces or special characters
- Duplicate Headers: Using
-Hmultiple times for the same header will override previous values