在C++中進行POST請求并接收響應通常需要使用一個HTTP庫,如cURL或cpp-netlib。下面是一個使用cURL庫進行POST請求并接收響應的示例:
#include <iostream>
#include <curl/curl.h>
size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* s)
{
size_t newLength = size * nmemb;
size_t oldLength = s->size();
try
{
s->resize(oldLength + newLength);
}
catch (std::bad_alloc &e)
{
//handle memory problem
return 0;
}
std::copy((char*)contents, (char*)contents + newLength, s->begin() + oldLength);
return size * nmemb;
}
int main()
{
CURL *curl;
CURLcode res;
curl = curl_easy_init();
std::string response;
if(curl)
{
curl_easy_setopt(curl, CURLOPT_URL, "https://example.com/api");
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "param1=value1¶m2=value2");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
if(res == CURLE_OK)
{
std::cout << "Response: " << response << std::endl;
}
else
{
std::cerr << "Error: " << curl_easy_strerror(res) << std::endl;
}
}
return 0;
}
在這個示例中,我們使用cURL庫來發送POST請求到"https://example.com/api"并傳遞參數"param1=value1¶m2=value2"。通過設置CURLOPT_WRITEFUNCTION
和CURLOPT_WRITEDATA
選項,我們將接收到的響應數據存儲在response
字符串中,并最終輸出到控制臺。