Poco SendHttpRequest PocoServer 2021-03-31

PocoServer

// PocoHttpServer.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <Poco/Net/HTTPRequestHandler.h>
#include <Poco/Net/HTTPRequestHandlerFactory.h>
#include <Poco/Net/HTTPServerRequest.h>
#include <Poco/Net/HTTPServerResponse.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/Net/HTTPServer.h>
#include <Poco/StreamCopier.h>
#include <Poco/Util/ServerApplication.h>

using Poco::Net::HTTPRequestHandler;
using Poco::Net::HTTPServerRequest;
using Poco::Net::HTTPServerResponse;
using Poco::Net::HTTPResponse;
using Poco::Net::HTTPRequestHandlerFactory;
using namespace Poco::Net;
using Poco::Util::ServerApplication;


// ANSI ==> UTF8
bool ANSI_to_UTF8(const std::string &sAnsi, std::string &sUtf8)
{
	if (sAnsi.empty())
		return true;
	std::wstring wsAnsi;
	int nLen = ::MultiByteToWideChar(CP_ACP, NULL, sAnsi.c_str(), -1, NULL, 0);
	wchar_t *buf1 = new wchar_t[nLen];
	int nWrited = ::MultiByteToWideChar(CP_ACP, NULL, sAnsi.c_str(), -1, buf1, nLen);
	wsAnsi = buf1;
	delete[] buf1;
	if (nWrited != nLen)
		return false;
	nLen = ::WideCharToMultiByte(CP_UTF8, NULL, wsAnsi.c_str(), -1, NULL, 0, NULL, NULL);
	char* buf2 = new char[nLen];
	nWrited = ::WideCharToMultiByte(CP_UTF8, NULL, wsAnsi.c_str(), -1, buf2, nLen, NULL, NULL);
	sUtf8 = buf2;
	delete[] buf2;
	return (nWrited == nLen) ? true : false;
}

/ Poco的HTTP服务端 /
class MyRequestHandler : public HTTPRequestHandler
{
public:
	virtual void handleRequest(HTTPServerRequest &req, HTTPServerResponse &resp)
	{
		std::string sUtf8;
		ANSI_to_UTF8("成功", sUtf8);
		std::istream& istr = req.stream();
		std::string sRequest;
		Poco::StreamCopier::copyToString(istr, sRequest);//获取请求内容
		resp.setStatus(HTTPResponse::HTTP_OK);
		resp.setContentType("application/x-www-form-urlencoded\r\n");
		ostream& out = resp.send();				//返回一个回复的流引用		
		out << "<h1>Hello world!</h1>" << "\r\n\r\n"
			<< "<p>Count: " << ++count		<< "</p>" << "\r\n\r\n"
			<< "<p>Host: " << req.getHost()	<< "</p>" << "\r\n\r\n"
			<< "<p>Method: " << req.getMethod() << "</p>" << "\r\n\r\n"
			<< "<p>URI: " << req.getURI() << "</p>" << "\r\n\r\n"
			<< "<p>ContentRequest: " << sRequest << "</p>" << "\r\n\r\n"
			<< sUtf8;
		out.flush();						//将这个信息会送到客户端	
	}
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> &)		//run函数里面调用这个mian()函数	
	{
		HTTPServer s(new MyRequestHandlerFactory, ServerSocket(9090), new HTTPServerParams);//创建一个具有多线程特性的服务器类,其实这个类才是这个程序的核心,它接受参数“工厂”,以及制定服务器端口 		
		s.start();
		cout << endl << "Server started" << endl;
		waitForTerminationRequest();  							//等待用户点击关闭按钮,此时一直运行着,阻塞在此 		
		cout << endl << "Shutting down..." << endl;
		s.stop();
		return Application::EXIT_OK;
	}
};

int _tmain(int argc, _TCHAR* argv[])
{
	MyServerApp app;
	return app.run(argc, argv);			//让服务器运行起来
}

PocoClient

// PocoHttpClient.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <Poco/Net/HTTPClientSession.h>
#include <Poco/URI.h>
#include <Poco/Net/HTTPRequest.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/Util/PropertyFileConfiguration.h>
#include <Poco/AutoPtr.h>
using Poco::AutoPtr;
using Poco::Util::PropertyFileConfiguration;


// 获取当前exe所在目录,不包括最后的"\"
CString GetExeDir();
bool IsPathExist(const CString& sPath);
BOOL SendHttpRequest();



int _tmain(int argc, _TCHAR* argv[])
{
	
	CString str = GetExeDir();
	bool b = IsPathExist(_T("E:\\111"));
	

	`PocoServer`();
	system("pause");
	return 0;
}

BOOL SendHttpRequest()
{
	/ Poco的HTTP客户端 //
	try
	{
		//std::string sInputXml("发送的内容。。。");
		//std::string sUrl("http://127.0.0.1:9090");
		AutoPtr<PropertyFileConfiguration> pfc = new PropertyFileConfiguration("Config/PocoHttpClient.properties");
		std::string sInputXml = pfc->getString("PocoHttpClient.ContentSended");
		std::string sUrl = pfc->getString("PocoHttpClient.Url");
		Poco::URI uri(sUrl);

		std::string path(uri.getPathAndQuery());
		path = uri.getPath();
		path = uri.getPathAndQuery();
		path = sUrl;

		Poco::Net::HTTPClientSession session(uri.getHost(), uri.getPort());
		int nTimeout = 20;
		Poco::Timespan pocoTimeSpan(nTimeout, 0);
		session.setTimeout(pocoTimeSpan);
		Poco::Net::HTTPRequest req(Poco::Net::HTTPRequest::HTTP_POST, path, Poco::Net::HTTPMessage::HTTP_1_1);
		//		Poco::Net::HTTPRequest req(Poco::Net::HTTPRequest::HTTP_POST);
		req.setChunkedTransferEncoding(false);
		req.setContentType("application/xml");//application/json
		req.setContentLength(sInputXml.length());
		session.sendRequest(req) << sInputXml;
		Poco::Net::HTTPResponse res;
		std::istream &is = session.receiveResponse(res);
		int nHttpStatus = res.getStatus();
		if (Poco::Net::HTTPResponse::HTTPStatus::HTTP_OK != nHttpStatus)
			return FALSE;
		std::istreambuf_iterator<char> eos;
		std::string sRes(std::istreambuf_iterator<char>(is), eos);
		cout << sRes << endl;

		return TRUE;
	}
	catch (Poco::TimeoutException e)
	{
		//CString strError;
		//strError.Format(_T("超时连接服务异常。Url:%s\r\n异常信息:%s"), strUrl, CString(CStringA(e.what())));
		//AfxMessageBox(strError, MB_ICONERROR);
		std::string s = e.what();
		s += " : " + e.message();
	}
	catch (Poco::Exception e)
	{
		//strError.Format(_T("连接服务异常。Url:%s\r\n异常信息:%s"), strUrl, CString(CStringA(e.what())));
		//AfxMessageBox(strError, MB_ICONERROR);
		std::string s = e.what();
		s += " : " + e.message();
	}
	return FALSE;
}

bool IsPathExist(const CString& strPath)
{
	return (-1 != _taccess(strPath, 0));
}

// 获取当前exe所在目录,不包括最后的"\"
CString GetExeDir()
{
	//extern int __argc;          /* count of cmd line args */
	//extern char ** __argv;      /* pointer to table of cmd line args */
	//extern wchar_t ** __wargv;  /* pointer to table of wide cmd line args */
	TCHAR exeDir[_MAX_PATH] = { 0 };
#ifdef _UNICODE
	_tcscpy(exeDir, __wargv[0]);
#else
	_tcscpy(exeDir, __argv[0]);
#endif
	_tcsrchr(exeDir, '\\')[0] = '\0';
	return CString(exeDir);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值