要在C++中使用第三方庫發(fā)送POST JSON請(qǐng)求,您可以選擇使用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)
{
// 目標(biāo)URL
std::string url = "https://your-api-url.com/endpoint";
// 構(gòu)造JSON數(shù)據(jù)
std::string json_data = R"({"key": "value"})";
// 設(shè)置請(qǐng)求頭
struct curl_slist* headers = NULL;
headers = curl_slist_append(headers, "Content-Type: application/json");
// 設(shè)置CURL選項(xiàng)
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);
// 發(fā)送請(qǐng)求
CURLcode res = curl_easy_perform(curl);
// 檢查錯(cuò)誤
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發(fā)送一個(gè)包含JSON數(shù)據(jù)的POST請(qǐng)求。請(qǐng)確保將https://your-api-url.com/endpoint
替換為實(shí)際的API終端。