#include 赞 踩 1、服务器端的实例: #include "stdafx.h" #include <iostream> #include <chrono> using namespace httplib; string ArrayToJson() writer.StartArray(); writer.StartObject(); writer.StartObject(); writer.EndArray(); return sb.GetString(); int main() Server svr; svr.Get("/hi", [&](const Request& /*req*/, Response& res) svr.Get("/stop", svr.listen("localhost", 1234); } 生成的json的数据如下: [ 2、客户端连接服务器端实例如下: #include "stdafx.h" #include <iostream> using namespace std; #include "rapidjson.h" void ParseArray(string strJson) int main() //解析当前的json 至此,一个简单的http服务器端客户端通信传输json数据实例就完成了 Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。
c++ http服务器客户端程序-传输json解析json数据(2)_c++ json通信
#include <cstdio>
#include "httplib.h"
#include "rapidjson.h"
#include "prettywriter.h" // for stringify JSON
#include "document.h"
using namespace std;
{
using namespace rapidjson;
StringBuffer sb;
PrettyWriter<StringBuffer> writer(sb);
writer.Key("name");
writer.String("xiaoming");
writer.EndObject();
writer.Key("name");
writer.String("xiaohua");
writer.EndObject();
}
{
string strJson = ArrayToJson();
ParseArray(strJson);
if (!svr.is_valid())
{
printf("server has an error...\n");
return -1;
}
{
res.set_content(strJson, "text/plain");
});
[&](const Request& /*req*/, Response& /*res*/) { svr.stop(); });
int yy = 55;
{
"name": "xiaoming"
},
{
"name": "xiaohua"
}
]
#include "httplib.h"
#include <iostream>
#include "prettywriter.h" // for stringify JSON
#include "document.h"
using namespace std;
{
//创建解析对象
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();
}
}
}
{
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;
ParseArray(res->body);
}
else
{
}
system("pause");
}