restClient - cpp调用restfulapi的简单尝试

1 参考项目

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

2 依赖下载

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

1
2
3
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

#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;
}

执行情况如下:

1
2
3
4
5
6
7
8
9
10
11
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.