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:
bashcurl [options] [URL]
Example: Retrieving Web Content
Suppose we need to retrieve sample data from httpbin.org, we can use the following command:
bashcurl 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:
bashcurl -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.
bashcurl -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.
bashcurl 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.
bashcurl -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.