溫馨提示×

c++ post請求如何發送

c++
小樊
253
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女