要在C++中使用第三方库发送POST JSON请求,您可以选择使用libcurl或者cpprestsdk(Casablanca)等库
sudo apt-get install libcurl4-openssl-dev
main.cpp
的文件,并添加以下代码:#include<iostream>
#include<string>
#include <curl/curl.h>
size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp)
{
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}
int main()
{
CURL* curl = curl_easy_init();
if (curl)
{
// 目标URL
std::string url = "https://your-api-url.com/endpoint";
// 构造JSON数据
std::string json_data = R"({"key": "value"})";
// 设置请求头
struct curl_slist* headers = NULL;
headers = curl_slist_append(headers, "Content-Type: application/json");
// 设置CURL选项
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_data.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
std::string response;
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
// 发送请求
CURLcode res = curl_easy_perform(curl);
// 检查错误
if (res != CURLE_OK)
{
std::cerr << "Error: "<< curl_easy_strerror(res)<< std::endl;
}
else
{
std::cout << "Response: "<< response<< std::endl;
}
// 清理
curl_easy_cleanup(curl);
curl_slist_free_all(headers);
}
return 0;
}
g++ -o main main.cpp -lcurl
./main
这将向指定的URL发送一个包含JSON数据的POST请求。请确保将https://your-api-url.com/endpoint
替换为实际的API终端。