当前位置: 首页 > 工具软件 > Restc > 使用案例 >

cpp调用restapi的简单尝试 - restc-cpp client

汪翰墨
2023-12-01

1 参考项目

restClient in cpp: https://github.com/jgaa/restc-cpp

2 编译restClient的依赖下载

openssl下载:
https://github.com/CristiFati/Prebuilt-Binaries/blob/master/OpenSSL/v1.1.1/OpenSSL-1.1.1o-Win-pc064.zip

3 创建云端mock

个人示例:https://mock.apifox.cn/m1/1153222-0-default/roomlist

nash5@DESKTOP-0DDCG1U MINGW64 /f/myFiles/blogs (main)
$ curl  https://mock.apifox.cn/m1/1153222-0-default/roomlist
[{"id":1,"name":"room1"}]

4 示例代码以及测试

安装docker,执行restc-cpp的create_container脚本,然后修改:运行BasicTests.cpp


#include <iostream>

#include "restc-cpp/logging.h"

#include <boost/lexical_cast.hpp>
#include <boost/fusion/adapted.hpp>

#include "restc-cpp/restc-cpp.h"
#include "restc-cpp/RequestBuilder.h"

#include "restc-cpp/test_helper.h"

using namespace std;
using namespace restc_cpp;


struct Room {
    int id = 0;
    string name;
};

BOOST_FUSION_ADAPT_STRUCT(
    Room,
    (int, id)
    (string, name)
)

const static string roomListUrl = "https://mock.apifox.cn/m1/1153222-0-default/roomlist";

void tryGetRoom(Context& ctx) {
    // Asynchronously fetch the entire data-set, and convert it from json
    // to C++ objects was we go.
    // We expcet a list of Post objects
    cout << "getting room now!" << endl;
    list<Room> room_list;
    SerializeFromJson(room_list, ctx.Get(GetDockerUrl(roomListUrl)));

    // Just dump the data.
    for (const auto& room: room_list) {
        RESTC_CPP_LOG_INFO_("Post id=" << room.id << ", title: " << room.name);
    }
}

int main(int argc, char *argv[]) {

    RESTC_CPP_TEST_LOGGING_SETUP("debug");

    try {
        

        auto rest_client = RestClient::Create();
        cout << "trying to get rooms" << endl;
        // auto future = rest_client->ProcessWithPromise(DoSomethingInteresting);
        auto future = rest_client->ProcessWithPromise(tryGetRoom);

        // Hold the main thread to allow the worker to do it's job
        future.get();
        return 0;
    } catch (const exception& ex) {
        RESTC_CPP_LOG_INFO_("main: Caught exception: " << ex.what());
    }

    return 0;
}

执行情况如下:

nash5@DESKTOP-0DDCG1U MINGW64 /f/prjs/restc-cpp/build/tests/functional/Release (master)
$ ./basic_tests.exe
trying to get rooms
[2022-06-21 17:24:14.729043] [0x00008d94] [debug]   Worker 0 is starting.
getting room now!
[2022-06-21 17:24:14.758042] [0x00008d94] [debug]   Connecting to 114.55.47.169:443
[2022-06-21 17:24:14.807048] [0x00008d94] [debug]   Sent GET request to 'https://mock.apifox.cn/m1/1153222-0-default/roomlist' {Connection f3f975c7-cbbb-44a4-8d0c-2c95450273e2 {TlsSocket
socket# 624 192.168.5.44:50487 <--> 114.55.47.169:443}}
[2022-06-21 17:24:14.888860] [0x00008d94] [info]    Post id=1, title: room1
[2022-06-21 17:24:14.888860] [0x00008d94] [debug]   Worker 0 is done.

 类似资料: