HTTP requests comprise a request line, headers, and a body. The request line specifies the HTTP method, URL, and HTTP version. Headers provide metadata about the request, including information like Content-Type and Accept, and can also be used to send data such as authentication tokens or custom information. The body carries the main data payload.

Data can be sent in an HTTP request through various methods, including:

  1. URL parameters in a GET request.
  2. Form data in a POST request.
  3. JSON data in a POST request.
  4. Multipart/form-data in a POST request.
  5. Form data in a PUT request.
  6. Metadata in headers, applicable across different types of requests.

cURL supports sending data via HTTP using various methods such as POST, GET, PUT, and DELETE. It accommodates multiple data formats, including JSON, URL-encoded, and multipart/form-data, and allows for additional information through headers.

Steps to send data in an HTTP request with cURL:

  1. Open the terminal.
  2. To send data as URL parameters in a GET request, use:
    $ curl "https://www.example.com/api?param1=value1&param2=value2"
  3. To send data as form data in a POST request, use:
    $ curl -d "param1=value1&param2=value2" https://www.example.com/api

    With the -d flag, cURL uses POST by default.

  4. If you need to send JSON data, use the following structure:
    $ curl -X POST -H "Content-Type: application/json" -d '{"key1":"value1", "key2":"value2"}' https://www.example.com/api

    Ensure that the Content-Type header is set to application/json when sending JSON payloads.

  5. To send data in a PUT request, use:
    $ curl -X PUT -d "param1=value1&param2=value2" https://www.example.com/api
  6. For sending data as multipart/form-data (such as file uploads), use:
    $ curl -F "file=@path_to_file" https://www.example.com/upload

    The -F flag makes cURL emulate a filled-in form in which a user has pressed the submit button. This causes cURL to POST data using the Content-Type multipart/form-data.

  7. To customize headers when sending data, use the -H flag followed by the header:
    $ curl -H "Authorization: Bearer YOUR_TOKEN" -d "param=value" https://www.example.com/api
  8. If you're dealing with an endpoint with SSL issues and wish to bypass them (mostly in development environments), use the –insecure flag:
    $ curl --insecure -d "param=value" https://www.example.com/api

    Using –insecure or its shorthand -k bypasses SSL certificate checks. This is risky in production environments.

Discuss the article:

Comment anonymously. Login not required.