C++ 使用nlohmann/json和cpp-httplib 完成post请求

最近公司要我项目里弄http 请求,我没用过。探索了这么点东西。

第一步:用vscode  和它的 rest client插件完成post。

在文件里填入大数据同事给我的内容,右键send request,就拉取到了这个车的点位们。

C++ 使用nlohmann/json和cpp-httplib 完成post请求_第1张图片

 第二步;开始写代码,文件目录如下,include里放了json的头文件。

 

C++ 使用nlohmann/json和cpp-httplib 完成post请求_第2张图片

 C++ 使用nlohmann/json和cpp-httplib 完成post请求_第3张图片

代码如下:测试http.cpp

#include 
#include "httplib.h"
#include 
#include 
#include 
using namespace std;
using json = nlohmann::json;
int main()
{
    using json = nlohmann::json;
    json j_patch = R"({
        "did": "BCT5901642495177",
        "gpsStartTime" : "2022-11-14 15:11:35",
        "gpsEndTime" : "2022-11-14 15:11:29",
        "desc" : false,
        "pageSize" : 86400,
        "startRowKey" : "",
        "showColumns" : [
            "2602",
                "2603",
                "3014"
        ] ,
        "filterList" : [
            {
                "column": "2601",
                    "op" : "eq",
                    "value" : "0",
                    "filterIfMissing" : true
            }
        ] ,
                "parseValue": false
})"_json;
    
#if 1
    // 创建HTTP client 对象
    httplib::Client cli("192.168.13.73", 30001);
    // 注意这里设置时间的话有2种方式,(time_t sec, time_t usec)
    //cli.set_connection_timeout(300);
    //cli.set_read_timeout(300);
    // 创建header
    httplib::Headers headers = {
            { "content-type", "application/json" }
    };
    //auto res = cli.Post("/post", headers, params);
    // 参数准备
    string strvalue = j_patch.dump();
    cout << strvalue << endl;
    // 发送请求
    auto res = cli.Post("/hbase/canList", headers, strvalue, "application/json");
    cout << res->status << endl;
    cout << res->body << endl;
#if 0
    // 把结果弄成json, 然后从json中取出data项,
    auto jj = json::parse(res->body);
    json hk = jj["data"];
    string ss = jj.dump();

    cout << ss << endl;
#endif 
}

前面参数json 部分还可以用另一种方式:

    json bodyParamJson;
    bodyParamJson["did"] = "YXZ2612204084017";
    bodyParamJson["gpsStartTime"] = "2000-01-13 00:00:00";
    bodyParamJson["gpsEndTime"] = "2099-01-13 23:59:59";
    bodyParamJson["desc"] = false;
    bodyParamJson["pageSize"] = 86400;
    bodyParamJson["startRowKey"] = "";
    bodyParamJson["parseValue"] = false;
    bodyParamJson["showColumns"] = R"([
        "2602",
        "2603",
        "3014"
    ])"_json;

    bodyParamJson["filterList"] = R"([
        {
            "column": "2601",
            "op": "eq",
            "value": "0",
            "filterIfMissing": true
        }
    ])"_json;

    string ss = bodyParamJson.dump();

这样就能配置param 参数了。

你可能感兴趣的:(C++基础,json,vscode,ide,c++,http)