- 1 year ago
Capturing the output from libcurl in a std::string in c++ under Windows
Comment
1 / 1
To capture the output from libcurl into a std::string
in C++ under Windows, you can use a custom write function and set it as the write callback for libcurl. Here's an example:
cpp#include <iostream>
#include <string>
#include <curl/curl.h>
size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* output)
{
size_t totalSize = size * nmemb;
output->append(static_cast<char*>(contents), totalSize);
return totalSize;
}
int main()
{
CURL* curl = curl_easy_init();
if (curl)
{
std::string response;
curl_easy_setopt(curl, CURLOPT_URL, "https://example.com");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
CURLcode res = curl_easy_perform(curl);
if (res == CURLE_OK)
{
std::cout << "Response: " << response << std::endl;
}
else
{
std::cerr << "Error: " << curl_easy_strerror(res) << std::endl;
}
curl_easy_cleanup(curl);
}
else
{
std::cerr << "Failed to initialize libcurl" << std::endl;
}
return 0;
}
In this example:
- The
WriteCallback
function is a custom write callback provided by you. It receives the data from libcurl and appends it to theoutput
string. - In the
main
function, aCURL*
handle is initialized usingcurl_easy_init()
. - The URL to request is set using
curl_easy_setopt(curl, CURLOPT_URL, "https://example.com")
. - The
WriteCallback
function is registered as the write callback usingcurl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback)
. - The
response
string is passed as the user-defined pointer usingcurl_easy_setopt(curl, CURLOPT_WRITEDATA, &response)
. - The request is performed using
curl_easy_perform(curl)
, and the response is captured in theresponse
string. - The response is then printed to the console if the request was successful.
Make sure to link against the appropriate libcurl library and include the necessary headers in your project. Adjust the URL and any additional libcurl options according to your specific requirements.
Note: This example uses libcurl's synchronous blocking API. If you need to handle asynchronous or non-blocking operations, you may need to utilize additional libcurl functionalities or libraries like libuv or Boost.Asio.