温馨提示×

c++ post请求如何发送

c++
小樊
143
2024-07-15 23:35:45
栏目: 编程语言

在C++中发送POST请求通常需要使用网络库,比如curl或者cpprestsdk。以下是使用cpprestsdk发送POST请求的示例代码:

#include <cpprest/http_client.h>

using namespace web;
using namespace web::http;
using namespace web::http::client;

int main() {
    // 创建一个http_client对象
    http_client client(U("http://example.com"));

    // 创建一个JSON对象
    json::value json_obj;
    json_obj[U("key1")] = json::value::string(U("value1"));
    json_obj[U("key2")] = json::value::number(123);

    // 创建一个HTTP请求
    http_request request(methods::POST);
    request.headers().set_content_type(U("application/json"));
    request.set_body(json_obj);

    // 发送请求并等待响应
    auto response = client.request(request).get();

    // 输出响应的状态码和内容
    std::wcout << response.status_code() << std::endl;
    std::wcout << response.to_string() << std::endl;

    return 0;
}

在上面的示例中,我们使用cpprestsdk创建了一个http_client对象,并发送了一个POST请求到http://example.com,请求的内容是一个JSON对象。发送请求后,我们等待响应,并输出了响应的状态码和内容。

请注意,你需要安装cpprestsdk库,并在编译时链接该库才能成功编译以上示例代码。

0