1、服务器端的实例:
#include "stdafx.h"
#include <iostream>
#include <chrono>
#include <cstdio>
#include "httplib.h"
using namespace httplib;
#include "rapidjson.h"
#include "prettywriter.h" // for stringify JSON
#include "document.h"
using namespace std;
string ArrayToJson()
{
using namespace rapidjson;
StringBuffer sb;
PrettyWriter<StringBuffer> writer(sb);
writer.StartArray();
writer.StartObject();
writer.Key("name");
writer.String("xiaoming");
writer.EndObject();
writer.StartObject();
writer.Key("name");
writer.String("xiaohua");
writer.EndObject();
writer.EndArray();
return sb.GetString();
}
int main()
{
string strJson = ArrayToJson();
ParseArray(strJson);
Server svr;
if (!svr.is_valid())
{
printf("server has an error...\n");
return -1;
}
svr.Get("/hi", [&](const Request& /*req*/, Response& res)
{
res.set_content(strJson, "text/plain");
});
svr.Get("/stop",
[&](const Request& /*req*/, Response& /*res*/) { svr.stop(); });
svr.listen("localhost", 1234);
int yy = 55;
}
生成的json的数据如下:
[
{
"name": "xiaoming"
},
{
"name": "xiaohua"
}
]
2、客户端连接服务器端实例如下:
#include "stdafx.h"
#include <iostream>
#include "httplib.h"
#include <iostream>
using namespace std;
#include "rapidjson.h"
#include "prettywriter.h" // for stringify JSON
#include "document.h"
using namespace std;
void ParseArray(string strJson)
{
//创建解析对象
rapidjson::Document doc;
//首先进行解析,没有解析错误才能进行具体字段的解析
if (!doc.Parse(strJson.data()).HasParseError())
{
const rapidjson::Value& docArray = doc.GetArray();
for (int i = 0; i < docArray.Size(); ++i)
{
string strValue = docArray[i]["name"].GetString();
}
}
}
int main()
{
httplib::Client cli("localhost", 1234);
if (auto res = cli.Get("/hi"))
{
cout << res->status << endl;
cout << res->get_header_value("Content-Type") << endl;
cout << res->body << endl;
//解析当前的json
ParseArray(res->body);
}
else
{
}
system("pause");
}
至此,一个简单的http服务器端客户端通信传输json数据实例就完成了