c++中post json请求的响应如何处理

avatar
作者
筋斗云
阅读量:0

在C++中,发送POST请求并处理JSON响应通常需要使用第三方库,例如libcurl(用于发送HTTP请求)和nlohmann/json(用于处理JSON数据)

sudo apt-get install libcurl4-openssl-dev # 安装libcurl 

然后,按照nlohmann/json的GitHub页面上的说明将其添加到项目中。

以下是一个使用libcurl发送POST请求并使用nlohmann/json处理JSON响应的示例:

#include<iostream> #include<string> #include <curl/curl.h> #include <nlohmann/json.hpp>  using json = nlohmann::json;  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 main() {     CURL* curl = curl_easy_init();     if (curl)     {         // 设置URL         curl_easy_setopt(curl, CURLOPT_URL, "https://api.example.com/endpoint");          // 设置POST请求         curl_easy_setopt(curl, CURLOPT_POST, 1L);          // 设置POST数据         std::string postData = R"({"key": "value"})";         curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postData.c_str());          // 设置回调函数         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);          // 存储响应         std::string response;         curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);          // 发送请求         CURLcode res = curl_easy_perform(curl);          // 检查错误         if (res != CURLE_OK)         {             std::cerr << "Error: "<< curl_easy_strerror(res)<< std::endl;         }         else         {             // 解析JSON响应             try             {                 json j = json::parse(response);                 std::cout << "JSON Response:"<< std::endl;                 std::cout << j.dump(4)<< std::endl;             }             catch (const json::parse_error& e)             {                 std::cerr << "Error parsing JSON: " << e.what()<< std::endl;             }         }          // 清理         curl_easy_cleanup(curl);     }      return 0; } 

这个示例首先初始化一个libcurl会话,然后设置URL、POST请求和POST数据。接着,它设置一个回调函数来处理响应,并将响应存储在一个字符串中。最后,它发送请求并解析JSON响应。

注意:在实际项目中,你可能需要根据实际情况修改错误处理和异常处理。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!