我一直致力于使用WinHTTP和WinInet的HTTP客户端,并且最近考虑切换到POCO,因为它为HTTP实现提供了最好的API。通过HTTPS从POCO StreamCopier获取文件下载进度
我做了它的工作,但问题是我想通过定期查询流或通过某些事件处理知道文件的下载进度。
开始搜索可以做到这一点的API,然后遇到了这个Http upload with progress info, in C++ (Poco/Boost),谈到使用CountingOutputStream获取文件上传场景的进度。我觉得这是不完整的,并没有按照我的预期那样做,根本没有使用CountingStream的实际实现。
我知道可以通过CountingInputStream实现,但我不知道如何通过HttpStreamFactory打开的调用返回流。是否有可能使用它读取多个块中的流?或者定期查询读取的数据量,以便我可以通知UI?
这是我的代码:
bool HttpClientConnection::DownloadFile (const std::string& file_url, const std::string file_location)
{
try
{
std::string complete_page_url = "";
std::ofstream file_stream;
std::unique_ptr<std::istream> pStr = nullptr;
if (isSecureConnection)
{
complete_page_url = "https://";
}
else
{
complete_page_url = "http://";
}
{
complete_page_url = serverHostName + file_url;// assuming the file url itself will contain leading forward slash
}
// Create the URI from the URL to the file.
URI uri(complete_page_url);
//std::auto_ptr<std::istream>pStr(URIStreamOpener::defaultOpener().open(uri);
//StreamCopier::copyStream(*pStr.get(), std::cout);
if (isSecureConnection)
{
std::unique_ptr<HTTPSStreamFactory> https_stream_factory = nullptr;
if (_buseProxy)
{
https_stream_factory = std::unique_ptr<HTTPSStreamFactory>(new HTTPSStreamFactory(proxyHostName, proxyPort, getProxyUserName(), getProxyPassword()));
}
else
{
https_stream_factory = std::unique_ptr<HTTPSStreamFactory>(new HTTPSStreamFactory());
}
if (https_stream_factory)
{
pStr = std::unique_ptr<std::istream>(https_stream_factory->open(uri));
}
}
else
{
std::unique_ptr<HTTPStreamFactory> http_stream_factory = nullptr;
if (_buseProxy)
{
http_stream_factory = std::unique_ptr<HTTPStreamFactory>(new HTTPStreamFactory(proxyHostName, proxyPort, getProxyUserName(), getProxyPassword()));
}
else
{
http_stream_factory = std::unique_ptr<HTTPStreamFactory>(new HTTPStreamFactory());
}
if (http_stream_factory)
{
pStr = std::unique_ptr<std::istream>(http_stream_factory->open(uri));
}
}
if (pStr)
{
file_stream.open(file_location, ios::out | ios::trunc | ios::binary);
StreamCopier::copyStream(*pStr.get(), file_stream);
file_stream.close();
}
return true;
}
catch (Exception& exc)
{
if (httpLogger)
{
httpLogger->log(dcLogger::LOG_INFO, "HttpClient:: Exception in DownloadFile , error code: %d", exc.code());
}
}
return false;
}