c++怎么发送post请求

avatar
作者
筋斗云
阅读量:0

在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&param2=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字符串中,可以根据需要进行处理。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!