1、服务器端的实例:
#include "stdafx.h"
#include <iostream>
#include <chrono>
#include <cstdio>
#include "httplib.h"
using namespace httplib;
using namespace std;
#include "pugixml/pugixml.cpp"
struct xml_string_writer : pugi::xml_writer
{
std::string result;
virtual void write(const void* data, size_t size)
{
result += std::string(static_cast<const char*>(data), size);
}
};
string WriteXML()
{
using namespace pugi;
pugi::xml_document doc;
pugi::xml_node root_node = doc.append_child("Root");
pugi::xml_node students_node = root_node.append_child("students");
pugi::xml_node student_node = students_node.append_child("student");
pugi::xml_node name_node = student_node.append_child("name");
name_node.append_child(pugi::node_pcdata).set_value("2222");
xml_string_writer _str;
doc.save(_str);
return _str.result;
}
int main()
{
string strXML = WriteXML();
Server svr;
if (!svr.is_valid())
{
printf("server has an error...\n");
return -1;
}
svr.Get("/", [=](const Request& /*req*/, Response& res)
{
res.set_redirect("/hi");
});
svr.Get("/hi", [&](const Request& /*req*/, Response& res)
{
res.set_content(strXML, "text/plain");
});
svr.Get("/stop",
[&](const Request& /*req*/, Response& /*res*/) { svr.stop(); });
svr.listen("localhost", 1234);
}
2、客户端实例:
void ReadXML(string strXML)
{
std::locale::global(std::locale("chs"));
using namespace pugi;
pugi::xml_document doc;
doc.load_string(strXML.c_str());
pugi::xml_node tools = doc.first_child();
/*pugi::xml_node tools = doc.child("Root");*/
for (pugi::xml_node_iterator it = tools.begin(); it != tools.end(); ++it)
{
const char *strnode = it->name();
int tt = 66;
}
}
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
ReadXML(res->body);
}
else
{
}
system("pause");
}
至此,一个简单的http服务器端客户端通信传输xml数据实例就完成了