#include <iostream>
#include <curl/curl.h>
// 回调函数,用于处理响应数据
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() {
// 初始化 libcurl
curl_global_init(CURL_GLOBAL_DEFAULT);
// 设置请求 URL
std::string url = "http://example.com/post";
// 准备 JSON 数据
std::string json = "{\"name\": \"John\", \"age\": 30}";
// 发送 POST 请求
CURL* curl = curl_easy_init();
if (curl) {
// 设置请求头
struct curl_slist* headers = NULL;
headers = curl_slist_append(headers, "Content-Type: application/json");
// 设置请求选项
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);
// 执行请求
CURLcode res = curl_easy_perform(curl);
if (res != CURLE_OK) {
std::cout << "Failed to send POST request: " << curl_easy_strerror(res) << std::endl;
}
// 获取响应结果
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);
// 输出请求的响应结果
std::cout << "HTTP Status Code: " << http_code << std::endl;
std::cout << "Response Data: " << response_data << std::endl;
// 释放资源
curl_easy_cleanup(curl);
}
// 清理 libcurl
curl_global_cleanup();
return 0;
}