Mastering cURL – A Comprehensive Guide to HTTP Requests

Curl Commands Techhyme

cURL, short for “Client for URLs,” is a versatile command-line tool used for making HTTP requests to various destinations. It supports a wide range of protocols and is particularly popular for its simplicity and flexibility.

In this article, we’ll explore some common cURL commands to perform different types of HTTP requests.

Basic GET Requests:

The simplest cURL command fetches the content of a URL using the GET method:

curl http://example.com

Adding the `-v` option provides more details about the request and response, making it useful for debugging:

curl http://example.com -v

Basic Authentication:

When dealing with protected resources, cURL allows for Basic Authentication by including the username and password in the URL:

curl http://admin:password@example.com/ -vvv

An alternative syntax is to use the `-u` option:

curl -u admin:password http://example.com/ -vvv

To follow redirection after authentication, you can use the `-L` option:

curl -u admin:password -L http://example.com/

GET Request with Parameters:

For requests with parameters, you can append them to the URL. Here’s an example:

curl -u admin:password 'http://example.com/search.php?port_code=us'

Making POST Requests:

To make a POST request, use the `-d` option to provide the data:

curl -d 'username=user&password=pass' -L http://example.com/login.php

For debugging purposes, you can include the `-v` option:

curl -d 'username=user&password=pass' -L http://example.com/login.php -v

Cookie Handling:

cURL supports cookies. To use cookies, you can specify a cookie jar file:

curl -d 'username=user&password=pass' -L --cookie-jar cookies.txt http://example.com/login.php

Specifying Content Type:

For requests with a specific content type, you can use the `-H` option:

curl -H 'Content-Type: application/json' -d '{ "username" : "user", "password" : "pass" }' http://example.com/login.php

Other HTTP Methods:

cURL supports various HTTP methods. To make an OPTIONS request:

curl -X OPTIONS http://example.com/ -vv

For file uploads using the PUT method:

curl -X PUT -d @test.txt http://example.com/test.txt -vv

To perform a DELETE request:

curl -X DELETE http://example.com/test.txt -vv

Understanding these cURL commands provides a solid foundation for interacting with web services and APIs from the command line. As you explore more advanced scenarios, you’ll appreciate cURL’s power and flexibility in handling a variety of HTTP requests.

You may also like:

Related Posts

Leave a Reply