温馨提示×

c++怎么发送post请求

c++
小亿
337
2023-12-08 22:21:51
栏目: 编程语言

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

0