C++ で POST リクエストを送信の方法
C++では、libcurlライブラリを利用することで、POSTリクエストを送信できます。以下に簡単なサンプルコードを示します。
#include <iostream>
#include <curl/curl.h>
// 回调函数,接收服务器响应的数据
size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* response)
{
size_t totalSize = size * nmemb;
response->append((char*)contents, totalSize);
return totalSize;
}
int main()
{
CURL* curl;
CURLcode res;
// 初始化curl
curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
if (curl) {
// 设置POST请求的URL
curl_easy_setopt(curl, CURLOPT_URL, "http://example.com/post");
// 设置POST数据
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "param1=value1¶m2=value2");
// 设置回调函数,接收服务器响应的数据
std::string response;
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
// 执行POST请求
res = curl_easy_perform(curl);
// 检查请求是否成功
if (res != CURLE_OK)
std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
else
std::cout << "Response: " << response << std::endl;
// 清理curl
curl_easy_cleanup(curl);
}
// 清理curl全局环境
curl_global_cleanup();
return 0;
}
このコードでは、curl_easy_setopt関数はcurlのさまざまなオプションを設定するために使用されています。CURLOPT_URLはリクエストのURLを設定し、CURLOPT_POSTFIELDSはPOSTデータを設定するために使用されています。WriteCallback関数はサーバーレスポンスのデータを受信し、それをresponse文字列に保存するために使用されています。curl_easy_perform関数はリクエストを実行するために使用されています。リクエストの結果はresponse文字列に格納され、必要に応じて処理できます。