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

How to send a header using a HTTP request through a cURL call?

1个答案

1

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:

bash
curl -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

  1. 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

shell
2. **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.

  1. 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

shell
This 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 -v option 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.

2024年7月24日 09:42 回复

你的答案