溫馨提示×

c++怎么發送post請求

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