When using cURL for HTTP requests, you can add custom HTTP headers using the -H or --header option. This feature is particularly useful when calling APIs or including additional information in HTTP requests, such as authentication details or content types.
Basic Syntax
The basic cURL command syntax for adding HTTP headers is as follows:
bashcurl -H "Header-Key: Header-Value" [other options] URL
Here, Header-Key is the key for the HTTP header, and Header-Value is the corresponding value.
Examples
-
Sending a Request with a User-Agent
To specify a custom user agent with cURL, use:
bash
curl -H "User-Agent: MyCustomUserAgent/1.0" http://example.com
shell2. **Sending Authentication Information** For APIs requiring basic authentication, send the encoded username and password via HTTP headers: ```bash curl -H "Authorization: Basic YWRtaW46cGFzc3dvcmQ=" http://example.com
Here, YWRtaW46cGFzc3dvcmQ= represents the Base64-encoded username and password.
-
Specifying Content Type
When sending JSON data using POST or PUT methods, set the content type to
application/json:bash
curl -X POST -H "Content-Type: application/json" -d '{"name": "John", "age": 30}' http://example.com/users
shellThis informs the server that the data is in JSON format. 4. **Adding Multiple Headers** To include multiple headers, specify each with a separate `-H` option: ```bash curl -H "Authorization: Bearer YourAccessToken" -H "Content-Type: application/json" http://example.com/api/data
Notes
- Ensure headers are correctly formatted and comply with HTTP protocol specifications.
- Special characters may require proper escaping or quoting in the shell.
- Using the
-voption displays header information in requests and responses, which is invaluable for debugging.
By leveraging the -H option in cURL, you can flexibly include any required HTTP headers in your HTTP requests.