Poco::Net::HTTPClientSession を使うと、HTTP プロトコルを使って、簡単にファイルを入手することができます。
ここでは、ファイル取得の一連の手順をクラス化したものを紹介します。
class HTTPGetter
HTTPGetter.h
・コンストラクタで host と port を指定。
・Get() 時に file path を指定すると、std::ostream に、その file の内容が戻る。
#include <string> #include <iostream> #include "Poco/Net/HTTPClientSession.h" class HTTPGetter { public: HTTPGetter(const std::string& host, Poco::UInt16 port = Poco::Net::HTTPSession::HTTP_PORT); ~HTTPGetter(); int Get(const std::string& path, std::ostream& ostr); private: HTTPGetter(); HTTPGetter(const HTTPGetter&); HTTPGetter& operator = (const HTTPGetter&); std::string mHost; Poco::UInt16 mPort; }; |
HTTPGetter.cpp
・Get() に失敗した時の exception は catch され、-1 のエラーが戻る。
#include <Poco/Net/HTTPRequest.h> #include <Poco/Net/HTTPResponse.h> #include <Poco/StreamCopier.h> #include "HTTPGetter.h" HTTPGetter::HTTPGetter(const std::string& host, Poco::UInt16 port) : mHost (host) , mPort (port) { } HTTPGetter::~HTTPGetter() { } int HTTPGetter::Get(const std::string& path, std::ostream& ostr) { try { const std::string myPath = ('/' == path.c_str()[0]) ? path:("/"+path); Poco::Net::HTTPClientSession session(mHost, mPort); Poco::Net::HTTPRequest req(Poco::Net::HTTPRequest::HTTP_GET, path, Poco::Net::HTTPMessage::HTTP_1_1); session.sendRequest(req); Poco::Net::HTTPResponse res; std::istream& rs = session.receiveResponse(res); Poco::StreamCopier::copyStream(rs, ostr); } catch (Poco::Exception& exc) { return -1; } return 0; } |
HTTPClientSessionTest.cpp
・http://poco.roundsquare.net/downloads/test.txt (一行のテキストファイル)を取得して、所要時間と共に表示。
#include <Poco/URI.h> #include <iostream> #include "HTTPGetter.h" #include "ScopedElapsedTime.h" #include "PrepareConsoleLogger.h" int main(int /*argc*/, char** /*argv*/) { PrepareConsoleLogger logger(Poco::Logger::ROOT, Poco::Message::PRIO_INFORMATION); Poco::URI uri("http://poco.roundsquare.net/downloads/test.txt"); { ScopedElapsedTime msg("HTTPGetter ", "start", "end"); HTTPGetter getter(uri.getHost(), uri.getPort()); getter.Get(uri.getPath(), std::cout); } return 0; } |
Results of execution
[0] HTTPGetter start --- This is a sample text file for HTTPClientSessionTest --- [0] Elepsed time = 87.686mSec [0] HTTPGetter end |
Downloads
・ここをクリックすると、makefile や VC++ プロジェクトなど一式がダウンロードできます。
(2013.05.31 updated)
・2010年5月5日からのダウンロード数:1107
Subversion
・フリーの Subversion ホスティングサービス Assemblaで、ソースコードを管理しています。
Reference
・http://pocoproject.org にある Applications のプレセンテーション。(PDF)
![]() |
Copyright © 2010 Round Square Inc. All rights reserved. |
---|
0 Comments.