如何在c++中構(gòu)建json數(shù)據(jù)并發(fā)送post請(qǐng)求

c++
小樊
81
2024-09-15 18:26:07

要在C++中構(gòu)建JSON數(shù)據(jù)并發(fā)送POST請(qǐng)求,您可以使用第三方庫(kù),例如nlohmann/json和libcurl

  1. 首先,安裝nlohmann/json庫(kù)。您可以通過(guò)訪問(wèn)https://github.com/nlohmann/json#integration 獲取有關(guān)如何將其添加到項(xiàng)目的信息。

  2. 安裝libcurl庫(kù)。您可以從 https://curl.se/download.html 下載源代碼并按照說(shuō)明進(jìn)行編譯和安裝。對(duì)于許多操作系統(tǒng),您還可以使用預(yù)編譯的包管理器(如apt、yum或brew)安裝libcurl。

  3. 在您的C++文件中,包含所需的頭文件:

#include<iostream>
#include<string>
#include <nlohmann/json.hpp>
#include <curl/curl.h>
  1. 編寫(xiě)一個(gè)函數(shù),該函數(shù)使用libcurl發(fā)送POST請(qǐng)求:
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 sendPostRequest(const std::string& url, const std::string& jsonData, std::string& response)
{
    CURL* curl = curl_easy_init();
    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonData.c_str());
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
        struct curl_slist* headers = NULL;
        headers = curl_slist_append(headers, "Content-Type: application/json");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

        CURLcode res = curl_easy_perform(curl);
        if (res != CURLE_OK) {
            std::cerr << "Error in sending POST request: "<< curl_easy_strerror(res)<< std::endl;
            return -1;
        }
        curl_easy_cleanup(curl);
    }
    return 0;
}
  1. 在主函數(shù)中創(chuàng)建JSON數(shù)據(jù)并發(fā)送POST請(qǐng)求:
int main()
{
    // 創(chuàng)建JSON數(shù)據(jù)
    nlohmann::json jsonData;
    jsonData["key1"] = "value1";
    jsonData["key2"] = "value2";
    std::string jsonString = jsonData.dump();

    // 發(fā)送POST請(qǐng)求
    std::string response;
    int result = sendPostRequest("https://your-api-endpoint.com", jsonString, response);
    if (result == 0) {
        std::cout << "Response: "<< response<< std::endl;
    } else {
        std::cerr << "Failed to send POST request."<< std::endl;
    }

    return 0;
}
  1. 編譯并運(yùn)行程序。確保鏈接libcurl庫(kù)。例如,在Linux上,您可以使用以下命令:
g++ main.cpp -o main -lcurl
./main

這將創(chuàng)建一個(gè)包含兩個(gè)鍵值對(duì)的JSON數(shù)據(jù),并將其發(fā)送到指定的API端點(diǎn)。

0