SoFunction
Updated on 2025-04-13

How to use C/C++ to call libcurl to debug messages

1. Introduction to libcurl debugging tool

libcurlIt is a powerful library for implementing HTTP requests in C/C++ (supports GET, POST, PUT, etc.). In order to debug request and response information,libcurlThe following functions are provided:

  • Enable detailed log output:useCURLOPT_VERBOSEPrint all transmitted information.
  • Custom debug callback function:useCURLOPT_DEBUGFUNCTIONCapture and process debug logs.
  • Output request header and request body:useCURLINFO_HEADER_OUTandCURLOPT_POSTFIELDSOutput a complete request.
  • Capture the response content:useCURLOPT_WRITEFUNCTIONSave the server response to the variable.

2. Output request message

Use CURLOPT_VERBOSE

CURLOPT_VERBOSEIt is the easiest debugging tool, by setting this option to1L, can makelibcurlOutput detailed transmission information, including request header and request body:

curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);

An example of the output content is as follows:

> POST /api HTTP/1.1
> Host: 
> Content-Type: application/json
> Content-Length: 29
>
* upload completely sent off: 29 out of 29 bytes

Use CURLOPT_DEBUGFUNCTION

If you need to control more control of debugging information, you can useCURLOPT_DEBUGFUNCTIONCustom processing logic, such as saving logs into files or strings.

Here is the code for custom debugging callback functions:

#include <iostream>
#include <string>
#include <curl/>
 
int DebugCallback(CURL* handle, curl_infotype type, char* data, size_t size, void* userptr) {
    std::string* log = static_cast<std::string*>(userptr);
 
    if (type == CURLINFO_HEADER_OUT) {
        log->append("[REQUEST HEADERS]:\n");
        log->append(data, size);
    } else if (type == CURLINFO_DATA_OUT) {
        log->append("[REQUEST BODY]:\n");
        log->append(data, size);
    }
 
    return 0;
}

3. Output response message

To capture the server's response, you can useCURLOPT_WRITEFUNCTIONSave the response to a variable:

size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* userp) {
    size_t totalSize = size * nmemb;
    userp->append((char*)contents, totalSize);
    return totalSize;
}

When configuring CURL options, add:

curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &responseString);

4. Complete code example

Here is a complete example showing how to uselibcurlSend HTTPS POST request and output detailed information of the request and response.

#include &lt;iostream&gt;
#include &lt;string&gt;
#include &lt;curl/&gt;
 
// Custom debug callback functionint DebugCallback(CURL* handle, curl_infotype type, char* data, size_t size, void* userptr) {
    std::string* log = static_cast&lt;std::string*&gt;(userptr);
 
    if (type == CURLINFO_HEADER_OUT) {
        log-&gt;append("[REQUEST HEADERS]:\n");
        log-&gt;append(data, size);
    } else if (type == CURLINFO_DATA_OUT) {
        log-&gt;append("[REQUEST BODY]:\n");
        log-&gt;append(data, size);
    }
 
    return 0;
}
 
// Callback function: Receive the server's response datasize_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* userp) {
    size_t totalSize = size * nmemb;
    userp-&gt;append((char*)contents, totalSize);
    return totalSize;
}
 
int main() {
    CURL* curl = curl_easy_init();
    if (!curl) {
        std::cerr &lt;&lt; "Failed to initialize CURL!" &lt;&lt; std::endl;
        return 1;
    }
 
    const std::string url = "/api";
    const std::string jsonData = R"({"key1":"value1", "key2":"value2"})";
    std::string responseString;
    std::string debugLog;  // Used to store debug logs 
    struct curl_slist* headers = nullptr;
    headers = curl_slist_append(headers, "Content-Type: application/json");
 
    // Set CURL options    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
    curl_easy_setopt(curl, CURLOPT_POST, 1L);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonData.c_str());
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &amp;responseString);
 
    // Enable debugging function    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
    curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, DebugCallback);
    curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &amp;debugLog);
 
    // Execute the request    CURLcode res = curl_easy_perform(curl);
    if (res != CURLE_OK) {
        std::cerr &lt;&lt; "CURL error: " &lt;&lt; curl_easy_strerror(res) &lt;&lt; std::endl;
    } else {
        std::cout &lt;&lt; "Response: " &lt;&lt; responseString &lt;&lt; std::endl;
    }
    // Output debug log    std::cout &lt;&lt; "\n===== Debug Log =====\n" &lt;&lt; debugLog &lt;&lt; std::endl;
    curl_easy_cleanup(curl);
    curl_slist_free_all(headers);
    return 0;
}

5. Compile and run

Make sure it is installedlibcurl. Install on Ubuntu:

sudo apt-get install libcurl4-openssl-dev

Compile the code with the following command:

g++ -o post_debug post_debug.cpp -lcurl

Run the program:

./post_debug

6. Output example

After the program is run, request and response information will be output, such as:

Debug log

===== Debug Log =====
[REQUEST HEADERS]:
POST /api HTTP/1.1
Host: 
Content-Type: application/json
Content-Length: 29
 
[REQUEST BODY]:
{"key1":"value1", "key2":"value2"}

Response content

Response: {"status":"success","message":"Data received"}

Summarize

By enablingCURLOPT_VERBOSEOr customCURLOPT_DEBUGFUNCTION, can be easily viewedlibcurlrequest message (including request header and request body). Combined with the response callback function, it can fully debug HTTP requests and content returned by the server. These tools are very useful for developing and debugging network programs!

This is the article about how to use C/C++ to call libcurl to debug messages. For more related C/C++ to call libcurl to debug messages, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!