用惯了 Jetty 的 基于事件的 HttpClient 类,在C++平台上也没找到这样调用方式的类库,只好自己写一个了。
目前版本 1.0,朋友们看了给点建议。(注:Kylindai原创,转载请注明出处)
Feature: 基于C++跨平台的 POCO 库实现,支持线程池 Poco::ThreadPool, 异步 HttpClient, 支持Http事件回调处理。
基本思路,核心方法:
/**
* 创建多线程支持的HttpClient,
* nTimeout 超时
* nMaxThreads 最大线程数
* pLogFileName 日志文件
*/
CHttpClient.Create(int nTimeout, int nMaxThreads, char * pLogFileName = NULL);
/**
* 发送请求,此方法会创建一个 CHttpTask 放到线程池里,然后由线程发起 HTTPClientSession 请求,
* 收到响应后,回调 CHttpExchange.GetHandler().OnResponseComplate() 方法。
* 类似 Java Jetty的 HttpClient.send(HttpExchange exchange)
* pExchange CHttpExchange HTTP 交换类
*/
CHttpClient.Send(CHttpExchange * pExchange);
/**
* 为HttpExchange 设置 Handler 处理回调类,以后具体的逻辑由 CHttpHandler 继承的具体业务处理逻辑类完成。
* pHandler CHttpHandler HTTP 事件处理类
*/
CHttpExchange.SetHandler(CHttpHandler * pHandler);
/**
* 当收到响应完成时的事件回调函数,传入 HttpStatus 和 文本的Response,
* 目前仅支持文本 Response,即:Resonse.getContentType() 为 text 类型
*/
CHttpHandler.OnResponseComplate(HTTPResponse::HTTPStatus status, const string& responseContent);
(一)CHttpClient CHttpExchange CHttpHandler 类图:
(二)代码:
HttpClient.h
View Code 1 ////////////////////////////////////////////////////////////////////////// 2 // HttpClient.h 3 // Author: Kylin.dai @kylindai 4 // Date: 2011-05-21 5 ////////////////////////////////////////////////////////////////////////// 6 7 #pragma _disibledevent=> 8 9 #include "Poco/AutoPtr.h" 10 #include "Poco/Logger.h" 11 #include "Poco/PatternFormatter.h" 12 #include "Poco/FormattingChannel.h" 13 #include "Poco/ConsoleChannel.h" 14 #include "Poco/FileChannel.h" 15 #include "Poco/Message.h" 16 #include "Poco/Exception.h" 17 #include "Poco/StreamCopier.h" 18 #include "Poco/ThreadPool.h" 19 #include "Poco/Thread.h" 20 #include "Poco/Mutex.h" 21 #include "Poco/Runnable.h" 22 #include "Poco/Stopwatch.h" 23 #include "Poco/Net/HTTPClientSession.h" 24 #include "Poco/Net/HTTPRequest.h" 25 #include "Poco/Net/HTTPResponse.h" 26 27 #include
28 #include 29 #include 30 #include 31 #include
最新评论