cURL in C++: Usage Guide & Examples
cURL (Client for URLs) is a tool and library used for transferring data, supporting various protocols like HTTP, HTTPS, and FTP. In C++, the cURL library can be used for network communication, sending HTTP requests, and receiving HTTP responses.
Here is a simple example using the cURL library:
#include <curl/curl.h>
#include <iostream>
size_t writeCallback(void* contents, size_t size, size_t nmemb, std::string* buffer) {
size_t realsize = size * nmemb;
buffer->append((char*)contents, realsize);
return realsize;
}
int main() {
CURL* curl;
CURLcode res;
std::string buffer;
curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, "https://www.example.com");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
}
curl_easy_cleanup(curl);
}
std::cout << buffer << std::endl;
return 0;
}
In the example above, the first step includes the cURL header file and defines a write callback function. The cURL object is then initialized in the main function, the request URL is set, along with the write callback function and the buffer for writing data. The HTTP request is executed, the response is saved in the buffer, and finally, the response content is output.
It is important to note that when using the cURL library, you need to link the corresponding cURL library file. You can link the cURL library by adding the parameter -lcurl during compilation.
The example above only covers the basic usage of the cURL library, which has many other functions and options that can be achieved by setting different options, such as setting request headers, sending POST requests, etc. For more detailed instructions, please refer to the official cURL documentation.