Try it yourself with our free Curl Converter tool — runs entirely in your browser, no signup needed.

How to Make HTTP requests in C++

How to make HTTP requests in C++

Making HTTP requests is a fundamental task in many C++ applications, allowing you to interact with web servers, APIs, and other online resources. In this article, we'll explore how to make HTTP requests in C++ using the curl library, a popular and widely-used library for transferring data over HTTP.

Quick Example

Here's a minimal example that makes a GET request to a URL:

#include <curl/curl.h>

int main() {
    CURL *curl;
    CURLcode res;

    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();
    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "https://example.com");
        res = curl_easy_perform(curl);
        if(res != CURLE_OK) {
            std::cerr << "Error: " << curl_easy_strerror(res) << std::endl;
        }
        curl_easy_cleanup(curl);
    }
    curl_global_cleanup();

    return 0;
}

To compile and run this example, you'll need to install the libcurl4-openssl-dev package on Ubuntu-based systems:

sudo apt-get install libcurl4-openssl-dev

Then, compile the code with:

g++ -o example example.cpp -lcurl

Step-by-Step Breakdown

Let's walk through the code line by line:

  1. #include <curl/curl.h>: We include the curl header file to access the curl library.
  2. int main(): We define the main function, the entry point of our program.
  3. CURL *curl;: We declare a pointer to a CURL object, which represents the HTTP request.
  4. CURLcode res;: We declare a variable to store the result of the HTTP request.
  5. curl_global_init(CURL_GLOBAL_DEFAULT);: We initialize the curl library with the default settings.
  6. curl = curl_easy_init();: We create a new CURL object and store it in the curl pointer.
  7. if(curl) { ... }: We check if the curl object was successfully created.
  8. curl_easy_setopt(curl, CURLOPT_URL, "https://example.com");: We set the URL of the HTTP request using the CURLOPT_URL option.
  9. res = curl_easy_perform(curl);: We perform the HTTP request and store the result in the res variable.
  10. if(res != CURLE_OK) { ... }: We check if the HTTP request was successful.
  11. curl_easy_cleanup(curl);: We clean up the CURL object.
  12. curl_global_cleanup();: We clean up the curl library.

Handling Edge Cases

Here are a few common edge cases to consider:

Empty/Null Input

If the input URL is empty or null, the curl library will return an error. We can add a simple check to handle this case:

if(url.empty()) {
    std::cerr << "Error: Empty URL" << std::endl;
    return 1;
}

Invalid Input

If the input URL is invalid (e.g. contains invalid characters), the curl library will return an error. We can use the curl_easy_setopt function to set the CURLOPT_URL option and check the return value:

if(curl_easy_setopt(curl, CURLOPT_URL, url.c_str()) != CURLE_OK) {
    std::cerr << "Error: Invalid URL" << std::endl;
    return 1;
}

Large Input

If the input URL is very large, the curl library may return an error. We can use the curl_easy_setopt function to set the CURLOPT_URL option and check the return value:

if(curl_easy_setopt(curl, CURLOPT_URL, url.c_str()) != CURLE_OK) {
    std::cerr << "Error: URL too large" << std::endl;
    return 1;
}

Unicode/Special Characters

If the input URL contains Unicode or special characters, the curl library may return an error. We can use the curl_easy_setopt function to set the CURLOPT_URL option and check the return value:

if(curl_easy_setopt(curl, CURLOPT_URL, url.c_str()) != CURLE_OK) {
    std::cerr << "Error: URL contains invalid characters" << std::endl;
    return 1;
}

Common Mistakes

Here are a few common mistakes to avoid:

Mistake 1: Forgetting to Initialize the curl Library

// WRONG
CURL *curl;
curl = curl_easy_init();
// CORRECT
curl_global_init(CURL_GLOBAL_DEFAULT);
CURL *curl;
curl = curl_easy_init();

Mistake 2: Not Checking the Return Value of curl_easy_perform

// WRONG
curl_easy_perform(curl);
// CORRECT
CURLcode res = curl_easy_perform(curl);
if(res != CURLE_OK) {
    std::cerr << "Error: " << curl_easy_strerror(res) << std::endl;
}

Mistake 3: Not Cleaning Up the CURL Object

// WRONG
curl_easy_init();
// CORRECT
CURL *curl = curl_easy_init();
// ...
curl_easy_cleanup(curl);

Performance Tips

Here are a few performance tips to keep in mind:

  1. Reuse the CURL Object: Instead of creating a new CURL object for each HTTP request, reuse the same object to reduce overhead.
  2. Use the CURLOPT_KEEP_SEND_FUNCTION Option: This option allows the curl library to keep the send function open between requests, reducing overhead.
  3. Use the CURLOPT_MAX_SEND_SPEED_LARGE Option: This option sets the maximum send speed to a large value, allowing the curl library to transfer data more quickly.

FAQ

Q: What is the curl library?

A: The curl library is a C library for transferring data over HTTP.

Q: How do I install the curl library?

A: You can install the curl library using the libcurl4-openssl-dev package on Ubuntu-based systems.

Q: How do I make a POST request using the curl library?

A: You can make a POST request using the CURLOPT_POSTFIELDS option.

Q: How do I handle errors using the curl library?

A: You can handle errors using the curl_easy_strerror function.

Q: Can I use the curl library in a multithreaded environment?

A: Yes, the curl library is thread-safe and can be used in a multithreaded environment.

AI agent tools available. The CodeTidy MCP Server gives Claude, Cursor, and other AI agents access to 60+ developer tools. One command: npx @codetidy/mcp