c++

C++中如何发送POST请求

小樊
84
2024-09-06 10:15:00
栏目: 编程语言

在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请求并显示响应内容。

0
看了该问题的人还看了