c++

如何在c++中构建json数据并发送post请求

小樊
81
2024-09-15 18:26:07
栏目: 编程语言

要在C++中构建JSON数据并发送POST请求,您可以使用第三方库,例如nlohmann/json和libcurl

  1. 首先,安装nlohmann/json库。您可以通过访问https://github.com/nlohmann/json#integration 获取有关如何将其添加到项目的信息。

  2. 安装libcurl库。您可以从 https://curl.se/download.html 下载源代码并按照说明进行编译和安装。对于许多操作系统,您还可以使用预编译的包管理器(如apt、yum或brew)安装libcurl。

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

#include<iostream>
#include<string>
#include <nlohmann/json.hpp>
#include <curl/curl.h>
  1. 编写一个函数,该函数使用libcurl发送POST请求:
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. 在主函数中创建JSON数据并发送POST请求:
int main()
{
    // 创建JSON数据
    nlohmann::json jsonData;
    jsonData["key1"] = "value1";
    jsonData["key2"] = "value2";
    std::string jsonString = jsonData.dump();

    // 发送POST请求
    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. 编译并运行程序。确保链接libcurl库。例如,在Linux上,您可以使用以下命令:
g++ main.cpp -o main -lcurl
./main

这将创建一个包含两个键值对的JSON数据,并将其发送到指定的API端点。

0
看了该问题的人还看了