参考:
https://blog.csdn.net/wuu19/article/details/102977166
https://blog.csdn.net/liuwenchang1234/article/details/98874288?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.nonecase
http_server.cc
//#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace Poco::Net;
using namespace Poco::Util;
using namespace std;
class MyRequestHandler : public HTTPRequestHandler
{
public:
virtual void handleRequest(HTTPServerRequest &req, HTTPServerResponse &resp)
{
//if(req.payload)
resp.setStatus(HTTPResponse::HTTP_OK);
//resp.setContentType("text/html");
resp.setContentType("application/json");
//resp.add("Accept", "Agent-007");
//resp.add("User-Agent", "xxxxoooo");
//resp.setContentLength(body.length());
//resp.sendRequest(request) << body;
std::istream& client_body = req.stream();
int length_msg = req.getContentLength();
char buffer[1024] = {
0};
client_body.read(buffer,length_msg);
std::cout
<< " contenttype:"
<< req.getContentType()
<< " payload:"
//<< req.get("payload")
<< "\n";
ostream& out = resp.send();
nlohmann::json json_body;
json_body["msg_id"] = "10086";
json_body["code"] = "0";
json_body["remark"] = "hello? yes,you got it!";
std::string body = json_body.dump();
out << body;
out.flush();
std::cout
<< " bd:"
<< buffer
<< "\n";
/*
*out << "Hello world!"
* << "Count: "
<< ++count << ""
* << "Host: "
<< req.getHost() << ""
* << "Method: "
<< req.getMethod() << ""
* << "URI: "
<< req.getURI() << "";
*out.flush();
*/
cout << endl
<< "Response sent for count=" << count
<< " and URI=" << req.getURI() << endl;
}
private:
static int count;
};
int MyRequestHandler::count = 0;
class MyRequestHandlerFactory : public HTTPRequestHandlerFactory
{
public:
virtual HTTPRequestHandler* createRequestHandler(const HTTPServerRequest &)
{
return new MyRequestHandler;
}
};
class MyServerApp : public ServerApplication
{
protected:
int main(const vector<string> &)
{
HTTPServer s(new MyRequestHandlerFactory, ServerSocket(9090), new HTTPServerParams);
s.start();
cout << endl << "Server started" << endl;
waitForTerminationRequest(); // wait for CTRL-C or kill
cout << endl << "Shutting down..." << endl;
s.stop();
return Application::EXIT_OK;
}
};
int main(int argc, char** argv)
{
MyServerApp app;
return app.run(argc, argv);
}
http_client.cc
//
// httpget.cpp
//
// This sample demonstrates the HTTPClientSession and the HTTPCredentials classes.
//
// Copyright (c) 2005-2012, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
//#include "Poco/JSON/Parser.h"//no this header in our env
#include
#include "Poco/Net/HTTPClientSession.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h"
#include
#include "Poco/StreamCopier.h"
#include "Poco/NullStream.h"
#include "Poco/Path.h"
#include "Poco/URI.h"
#include "Poco/Exception.h"
#include "Poco/Net/HTMLForm.h"
#include
bool doRequest(Poco::Net::HTTPClientSession& session, Poco::Net::HTTPRequest& request, Poco::Net::HTTPResponse& response)
{
session.sendRequest(request);
std::istream& rs = session.receiveResponse(response);
std::cout << response.getStatus() << " " << response.getReason() << std::endl;
if (response.getStatus() != Poco::Net::HTTPResponse::HTTP_UNAUTHORIZED)
{
Poco::StreamCopier::copyStream(rs, std::cout);
return true;
}
else
{
Poco::NullOutputStream null;
Poco::StreamCopier::copyStream(rs, null);
return false;
}
}
int main(int argc, char** argv)
{
try
{
// json
//std::string body("{key:value}");
//std::string json = "{ \"test\" : { \"property\" : \"value\" } }";
nlohmann::json json_body;
json_body["msg_id"] = "10086";
json_body["msg_type"] = "robot_app_control";
json_body["payload"] = "{ \"action\" : \"start\" , \"context\" : \"helooooo\" }";
std::string body = json_body.dump();
/*
* std::string body="{
* \"msg_id\": \"xxx\",
* \"msg_type\": \"robot_app_control\",
* \"payload\":
* {
* \"action\":\"stop/start\",
* \"context\":{\"token\":\"dfasf23aasdf14dfgdsg546fcg346\"}
* }
* }";
*
*/
// uri
//Poco::URI uri("http://www.baidu.com/test");
Poco::URI uri("http://127.0.0.1:9090/");
//Poco::URI uri("http://127.0.0.1:9091/");
// session
Poco::Net::HTTPClientSession session(uri.getHost(), uri.getPort());
session.setKeepAlive(true);
// request
Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_POST, uri.getPathAndQuery(), Poco::Net::HTTPRequest::HTTP_1_1);
request.setContentType("application/json");
request.add("Accept", "Agent-007");
request.add("User-Agent", "xxxxoooo");
request.setContentLength(body.length());
//
session.sendRequest(request) << body;
// response
Poco::Net::HTTPResponse res;
std::istream & is = session.receiveResponse(res);
int result = (int)res.getStatus();
std::cout << "result:" << result << ", reason:" << res.getReason() << std::endl;
std::string recv_string;
Poco::StreamCopier::copyToString(is, recv_string);
std::cout << "recv : " << std::endl << recv_string << std::endl;
//nlohmann::json js = nlohmann::json::parse(is);
nlohmann::json js = nlohmann::json::parse(recv_string);
std::string recv_code = js.at("code");
std::cout << "recv_code : " << std::endl << recv_code << std::endl;
}
catch (Poco::Exception& exc)
{
std::cerr << exc.displayText() << std::endl;
return 1;
}
return 0;
}
编译和测试现象
g++ -o http_server http_server.cc -lPocoNet -lPocoFoundation -lPocoUtil
g++ -o http_client http_client.cc -lPocoNet -lPocoFoundation
运行:
#一个终端
./http_server
Server started
contenttype:application/json payload:
bd:{
"msg_id":"10086","msg_type":"robot_app_control","payload":"{ \"action\" : \"start\" , \"context\" : \"helooooo\" }"}
Response sent for count=0 and URI=/
#另一个终端
./http_client result:200, reason:OK
recv :
{
"code":"0","msg_id":"10086","remark":"hello? yes,you got it!"}
recv_code :
0
client 请求的数据server获得了,并打印,取出来其中一个。
server回复了,client正常获取并打印。
清理没用代码:
http_server.cc
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace Poco::Net;
using namespace Poco::Util;
using namespace std;
class MyRequestHandler : public HTTPRequestHandler
{
public:
virtual void handleRequest(HTTPServerRequest &req, HTTPServerResponse &resp)
{
resp.setStatus(HTTPResponse::HTTP_OK);
//resp.setContentType("text/html");
resp.setContentType("application/json");
//resp.add("Accept", "Agent-007");
//resp.add("User-Agent", "xxxxoooo");
//resp.setContentLength(body.length());
//resp.sendRequest(request) << body;
std::istream& client_body = req.stream();
int length_msg = req.getContentLength();
char buffer[1024] = {
0};
client_body.read(buffer,length_msg);
std::cout
<< " contenttype:"
<< req.getContentType()
<< " payload:"
//<< req.get("payload")
<< "\n";
ostream& out = resp.send();
nlohmann::json json_body;
json_body["msg_id"] = "10086";
json_body["code"] = "0";
json_body["remark"] = "hello? yes,you got it!";
std::string body = json_body.dump();
out << body;
out.flush();
std::cout
<< " bd:"
<< buffer
<< "\n";
cout << endl
<< "Response sent for count=" << count
<< " and URI=" << req.getURI() << endl;
}
private:
static int count;
};
int MyRequestHandler::count = 0;
class MyRequestHandlerFactory : public HTTPRequestHandlerFactory
{
public:
virtual HTTPRequestHandler* createRequestHandler(const HTTPServerRequest &)
{
return new MyRequestHandler;
}
};
class MyServerApp : public ServerApplication
{
protected:
int main(const vector<string> &)
{
HTTPServer s(new MyRequestHandlerFactory, ServerSocket(9090), new HTTPServerParams);
s.start();
cout << endl << "Server started" << endl;
waitForTerminationRequest(); // wait for CTRL-C or kill
cout << endl << "Shutting down..." << endl;
s.stop();
return Application::EXIT_OK;
}
};
int main(int argc, char** argv)
{
MyServerApp app;
return app.run(argc, argv);
}
http_client.cc
#include
#include "Poco/Net/HTTPClientSession.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h"
#include
#include "Poco/StreamCopier.h"
#include "Poco/NullStream.h"
#include "Poco/Path.h"
#include "Poco/URI.h"
#include "Poco/Exception.h"
#include "Poco/Net/HTMLForm.h"
#include
bool doRequest(Poco::Net::HTTPClientSession& session, Poco::Net::HTTPRequest& request, Poco::Net::HTTPResponse& response)
{
session.sendRequest(request);
std::istream& rs = session.receiveResponse(response);
std::cout << response.getStatus() << " " << response.getReason() << std::endl;
if (response.getStatus() != Poco::Net::HTTPResponse::HTTP_UNAUTHORIZED)
{
Poco::StreamCopier::copyStream(rs, std::cout);
return true;
}
else
{
Poco::NullOutputStream null;
Poco::StreamCopier::copyStream(rs, null);
return false;
}
}
int main(int argc, char** argv)
{
try
{
// json
nlohmann::json json_body;
json_body["msg_id"] = "10086";
json_body["msg_type"] = "robot_app_control";
json_body["payload"] = "{ \"action\" : \"start\" , \"context\" : \"helooooo\" }";
std::string body = json_body.dump();
// uri
//Poco::URI uri("http://www.baidu.com/test");
Poco::URI uri("http://127.0.0.1:9090/");
// session
Poco::Net::HTTPClientSession session(uri.getHost(), uri.getPort());
session.setKeepAlive(true);
// request
Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_POST, uri.getPathAndQuery(), Poco::Net::HTTPRequest::HTTP_1_1);
request.setContentType("application/json");
request.add("Accept", "Agent-007");
request.add("User-Agent", "xxxxoooo");
request.setContentLength(body.length());
session.sendRequest(request) << body;
// response
Poco::Net::HTTPResponse res;
std::istream & is = session.receiveResponse(res);
int result = (int)res.getStatus();
std::cout << "result:" << result << ", reason:" << res.getReason() << std::endl;
std::string recv_string;
Poco::StreamCopier::copyToString(is, recv_string);
std::cout << "recv : " << std::endl << recv_string << std::endl;
//nlohmann::json js = nlohmann::json::parse(is);
nlohmann::json js = nlohmann::json::parse(recv_string);
std::string recv_code = js.at("code");
std::cout << "recv_code : " << std::endl << recv_code << std::endl;
}
catch (Poco::Exception& exc)
{
std::cerr << exc.displayText() << std::endl;
return 1;
}
return 0;
}