Using Curl to Retrieve HTTP Status Codes and Responses

Curl is a powerful command-line tool used for transferring data to and from a web server using various protocols, including HTTP. When working with web servers, it’s often necessary to retrieve not only the response body but also the HTTP status code and headers. In this tutorial, we’ll explore how to use curl to achieve this.

Retrieving HTTP Status Codes and Headers

By default, curl only retrieves the response body of an HTTP request. To include the HTTP status code and headers in the output, you can use the -i or --include option. This will display the protocol headers in the output, including the HTTP status code.

curl -i http://localhost

Alternatively, you can use the verbose mode (-v or --verbose) to make the operation more talkative and include additional information, such as the request and response headers.

curl -v http://localhost

Customizing Output with Variables

Curl allows you to customize the output using variables. The %{http_code} variable can be used to display the HTTP status code. You can use this variable in conjunction with the -w or --write-out option to specify a format string for the output.

curl -s -o response.txt -w "%{http_code}" http://example.com

This command will write the response body to a file named response.txt and display the HTTP status code on the console.

Capturing HTTP Status Code and Response Body

To capture both the HTTP status code and the response body, you can use the following approach:

http_response=$(curl -s -o response.txt -w "%{http_code}" http://example.com)
if [ $http_response != "200" ]; then
    # handle error
else
    echo "Server returned:"
    cat response.txt    
fi

This script will write the response body to a file named response.txt and store the HTTP status code in the http_response variable. You can then use this variable to check the status code and handle any errors accordingly.

Conclusion

In conclusion, curl provides several options for retrieving HTTP status codes and responses. By using the -i, -v, or -w options, you can customize the output to include the information you need. Additionally, by using variables like %{http_code}, you can capture specific pieces of information and use them in your scripts.

Leave a Reply

Your email address will not be published. Required fields are marked *