To perform an HTTP POST request in C++, you can use the cURL library. Here's an example of how you can make an HTTP POST request using cURL in C++:
#include <iostream> #include <string> #include <curl/curl.h> // Callback function to write response data into a string size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* response) { size_t totalSize = size * nmemb; response->append((char*)contents, totalSize); return totalSize; } int main() { CURL* curl; CURLcode res; std::string url = "https://example.com/api/endpoint"; std::string postData = "param1=value1¶m2=value2"; // POST data curl_global_init(CURL_GLOBAL_DEFAULT); curl = curl_easy_init(); if (curl) { // Set the URL curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); // Set the POST data curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postData.c_str()); // Set the callback function to write the response data into a string std::string response; curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); // Perform the request res = curl_easy_perform(curl); // Check for errors if (res != CURLE_OK) { std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl; } else { // Print the response std::cout << "Response: " << response << std::endl; } // Clean up curl_easy_cleanup(curl); } curl_global_cleanup(); return 0; }
In this example, we use the curl_easy_setopt()
function to set various options for the cURL request. We set the URL with CURLOPT_URL
, the POST data with CURLOPT_POSTFIELDS
, and the callback function to handle the response with CURLOPT_WRITEFUNCTION
and CURLOPT_WRITEDATA
. Finally, we perform the request with curl_easy_perform()
and handle any errors that occur.
Make sure to link against the cURL library by adding -lcurl
to your compiler flags when compiling the code.