Using cURL to Retrieve Only Response Headers

When working with HTTP requests, it’s often useful to retrieve only the response headers without downloading the full response body. This can be particularly helpful when dealing with large response bodies or when you’re only interested in the header information.

cURL is a powerful command-line tool that allows you to transfer data to and from a web server using various protocols, including HTTP. By default, cURL retrieves both the headers and the body of an HTTP response. However, there are several ways to use cURL to retrieve only the response headers.

Using the -I Option

The -I option tells cURL to fetch only the headers of a URL. This is equivalent to sending a HEAD request instead of a GET request. You can use this option with the curl command as follows:

curl -I http://example.com

This will retrieve only the response headers from the specified URL.

Using the -D Option

The -D option allows you to specify a file where cURL should write the protocol headers. By specifying a hyphen (-) as the filename, you can tell cURL to write the headers to stdout instead of a file:

curl -s -D - http://example.com > /dev/null

This will retrieve only the response headers and discard the response body.

Using the -X Option with -I

You can also use the -X option to specify a custom request method, such as POST. When combined with the -I option, this allows you to send a POST request and retrieve only the response headers:

curl -s -I -X POST http://example.com

This will send a POST request to the specified URL and retrieve only the response headers.

Following Redirects

If you want cURL to follow redirects when retrieving only the response headers, you can use the -L option in combination with the -I option:

curl -IL http://example.com

This will follow any redirects and retrieve only the response headers from the final URL.

Verbose Mode

If you want to see more detailed information about the request and response, including the full request and response headers, you can use the -v option:

curl -v http://example.com > /dev/null

This will display verbose output, including the full request and response headers.

In conclusion, cURL provides several ways to retrieve only the response headers of an HTTP request. By using the -I, -D, and -X options, you can customize your requests to suit your needs and avoid downloading unnecessary data.

Leave a Reply

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