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

HTTP POST and GET using cURL in Linux

1个答案

1

cURL is a commonly used command-line tool for data transfer, supporting various protocols including HTTP and HTTPS. When using cURL, you can send GET or POST requests by specifying different command-line options.

Sending GET Requests with cURL

Sending an HTTP GET request using cURL in Linux is straightforward. The basic command format is as follows:

bash
curl [options] [URL]

Example: Retrieving Web Content

Suppose we need to retrieve sample data from httpbin.org, we can use the following command:

bash
curl https://httpbin.org/get

This command outputs the JSON returned by httpbin.org, which includes request headers, referrer information, and other details.

Sending POST Requests with cURL

When sending a POST request, you need to specify the -X POST option and typically use -d to provide the POST data.

Example: Sending Form Data

Suppose we need to send form data to httpbin.org, we can use the following command:

bash
curl -X POST https://httpbin.org/post -d "name=John&age=30"

This command uses the -d option to send data, indicating that the POST request content is name=John&age=30. httpbin.org will return a response containing the provided form data.

Advanced Usage

Sending JSON Data

When sending JSON data, it is usually necessary to set Content-Type to application/json and use -d to provide the JSON string.

bash
curl -X POST https://httpbin.org/post -H "Content-Type: application/json" -d '{"name": "John", "age": 30}'

Saving Response to a File

If you need to save the response to a file instead of directly outputting it to the terminal, you can use the -o option.

bash
curl https://httpbin.org/get -o response.txt

In this way, the response to the GET request will be saved to the response.txt file.

Using Authentication

If you need to perform basic authentication for an HTTP service, you can use the -u option.

bash
curl -u username:password https://example.com

Conclusion

cURL is a powerful tool suitable for various data transfer tasks. By properly configuring command-line options, you can flexibly send various HTTP requests. In practical applications, understanding how to construct these requests is crucial for effective data interaction.

2024年6月29日 12:07 回复

你的答案