C++中如何发送POST请求
导读:在C++中,你可以使用第三方库如libcurl来发送POST请求 sudo apt-get install libcurl4-openssl-dev 接下来,编写一个简单的C++程序来发送POST请求: #include<iostr...
在C++中,你可以使用第三方库如libcurl来发送POST请求
sudo apt-get install libcurl4-openssl-dev
接下来,编写一个简单的C++程序来发送POST请求:
#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
curl_easy_setopt(curl, CURLOPT_URL, "https://example.com/api");
// 设置POST请求
curl_easy_setopt(curl, CURLOPT_POST, 1L);
// 设置POST数据
std::string postData = "key1=value1&
key2=value2";
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postData.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);
}
return 0;
}
这个示例向https://example.com/api
发送一个POST请求,并将响应内容输出到控制台。请确保将URL替换为你要发送请求的实际API地址。
要编译此程序,请使用以下命令:
g++ -o post_request post_request.cpp -lcurl
然后运行生成的可执行文件:
./post_request
这将发送一个POST请求并显示响应内容。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: C++中如何发送POST请求
本文地址: https://pptw.com/jishu/697987.html