#include <iostream>
#include <curl/curl.h>
// Callback function to process response data
int write_callback(char* data, size_t size, size_t nmemb, std::string* buffer) {
int result = 0;
if (buffer != nullptr) {
buffer->append(data, size * nmemb);
result = size * nmemb;
}
return result;
}
int main() {
// Initialize libcurl
curl_global_init(CURL_GLOBAL_DEFAULT);
// Set the request URL
std::string url = "http://example.com/post";
// Prepare JSON data
std::string json = "{\"name\": \"John\", \"age\": 30}";
// Send a POST request
CURL* curl = curl_easy_init();
if (curl) {
// Set the request header
struct curl_slist* headers = NULL;
headers = curl_slist_append(headers, "Content-Type: application/json");
// Set request Options
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json.c_str());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
// Execute the request
CURLcode res = curl_easy_perform(curl);
if (res != CURLE_OK) {
std::cout << "Failed to send POST request: " << curl_easy_strerror(res) << std::endl;
}
// Get the response result
long http_code = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
std::string response_data;
curl_easy_getinfo(curl, CURLINFO_PRIVATE, &response_data);
// Output the response result of the request
std::cout << "HTTP Status Code: " << http_code << std::endl;
std::cout << "Response Data: " << response_data << std::endl;
// Free up resources
curl_easy_cleanup(curl);
}
// Clean up libcurl
curl_global_cleanup();
return 0;
}