c++

c++ post请求如何接收响应

小樊
129
2024-07-15 23:43:46
栏目: 编程语言

在C++中进行POST请求并接收响应通常需要使用一个HTTP库,如cURL或cpp-netlib。下面是一个使用cURL库进行POST请求并接收响应的示例:

#include <iostream>
#include <curl/curl.h>

size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* s)
{
    size_t newLength = size * nmemb;
    size_t oldLength = s->size();
    try
    {
        s->resize(oldLength + newLength);
    }
    catch (std::bad_alloc &e)
    {
        //handle memory problem
        return 0;
    }

    std::copy((char*)contents, (char*)contents + newLength, s->begin() + oldLength);
    return size * nmemb;
}

int main()
{
    CURL *curl;
    CURLcode res;
    curl = curl_easy_init();
    std::string response;

    if(curl)
    {
        curl_easy_setopt(curl, CURLOPT_URL, "https://example.com/api");
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "param1=value1&param2=value2");
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);

        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);

        if(res == CURLE_OK)
        {
            std::cout << "Response: " << response << std::endl;
        }
        else
        {
            std::cerr << "Error: " << curl_easy_strerror(res) << std::endl;
        }
    }

    return 0;
}

在这个示例中,我们使用cURL库来发送POST请求到"https://example.com/api"并传递参数"param1=value1&param2=value2"。通过设置CURLOPT_WRITEFUNCTIONCURLOPT_WRITEDATA选项,我们将接收到的响应数据存储在response字符串中,并最终输出到控制台。

0
看了该问题的人还看了