notes:poco httpserver and httpclient

这篇笔记介绍了如何利用Poco库创建HTTP服务器和HTTP客户端。通过参考相关文章,成功实现了客户端发送请求,服务器接收并处理数据,然后返回响应给客户端的过程。在编译和测试中,数据交换正常,达到了预期效果。为了简洁,已移除不必要的代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考:
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 <Poco/Net/ServerSocket.h>
#include <Poco/Net/HTTPServer.h>
#include <Poco/Net/HTTPRequestHandler.h>
#include <Poco/Net/HTTPRequestHandlerFactory.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/Net/HTTPServerRequest.h>
#include <Poco/Net/HTTPServerResponse.h>
#include <Poco/Util/ServerApplication.h>
#include <iostream>
#include <string>
#include <vector>
#include <nlohmann/json.hpp>

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!" 
     *    << "<p>Count: "  << ++count         << "</p>"
     *    << "<p>Host: "   << req.getHost()   << "</p>"
     *    << "<p>Method: " << req.getMethod() << "</p>"
     *    << "<p>URI: "    << req.getURI()    << "</p>";
     *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 <nlohmann/json.hpp>
#include "Poco/Net/HTTPClientSession.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h"
#include <Poco/Net/HTTPCredentials.h>
#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 <iostream>



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 <Poco/Net/HTTPServer.h>
#include <Poco/Net/HTTPRequestHandler.h>
#include <Poco/Net/HTTPRequestHandlerFactory.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/Net/HTTPServerRequest.h>
#include <Poco/Net/HTTPServerResponse.h>
#include <Poco/Util/ServerApplication.h>
#include <iostream>
#include <string>
#include <vector>
#include <nlohmann/json.hpp>

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 <nlohmann/json.hpp>
#include "Poco/Net/HTTPClientSession.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h"
#include <Poco/Net/HTTPCredentials.h>
#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 <iostream>

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值