c++ - UrlDownloadToFile 到内存

标签 c++ wininet

我正在使用 URLDownloadToFile() 将图像从 Web 服务器下载到我桌面上的目录。如果我不想将图像保存到磁盘,而是想将它们读入内存(如字节数组或 base64 字符串等),是否有类似于 URLDownloadToFile() 的函数可以实现此目的?

最佳答案

URLOpenStream() , URLOpenBlockingStream()URLOpenPullStream()它允许您下载到内存中。

从这三个中,URLOpenBlockingStream()似乎是最直接使用的,因为它返回一个 IStream 指针,您可以从中同步读取一个循环。尽管它不像 URLDownloadToFile() 那样是一个全能 函数,但使用起来并不难。

这是 URLOpenBlockingStream() 的完整示例控制台应用程序.它从 URL 下载并将响应写入标准输出。取而代之的是,您可以将响应存储在 std::vector 中,或者用它做任何您喜欢的事情。

#include <Windows.h>
#include <Urlmon.h>   // URLOpenBlockingStreamW()
#include <atlbase.h>  // CComPtr
#include <iostream>
#pragma comment( lib, "Urlmon.lib" )

struct ComInit
{
    HRESULT hr;
    ComInit() : hr( ::CoInitialize( nullptr ) ) {}
    ~ComInit() { if( SUCCEEDED( hr ) ) ::CoUninitialize(); } 
};

int main(int argc, char* argv[])
{
    ComInit init;

    // use CComPtr so you don't have to manually call Release()
    CComPtr<IStream> pStream;  

    // Open the HTTP request.
    HRESULT hr = URLOpenBlockingStreamW( nullptr, L"http://httpbin.org/headers", &pStream, 0, nullptr );
    if( FAILED( hr ) )
    {
        std::cout << "ERROR: Could not connect. HRESULT: 0x" << std::hex << hr << std::dec << "\n"; 
        return 1;
    }

    // Download the response and write it to stdout.
    char buffer[ 4096 ];
    do
    {
        DWORD bytesRead = 0;
        hr = pStream->Read( buffer, sizeof(buffer), &bytesRead );

        if( bytesRead > 0 )
        {
            std::cout.write( buffer, bytesRead );
        }
    } 
    while( SUCCEEDED( hr ) && hr != S_FALSE );

    if( FAILED( hr ) )
    {
        std::cout << "ERROR: Download failed. HRESULT: 0x" << std::hex << hr << std::dec << "\n";
        return 2;
    }

    std::cout << "\n";

    return 0;
}

关于c++ - UrlDownloadToFile 到内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44027725/

相关文章:

c++ - 在 std::stringstream 中将字符串与破折号对齐

c++ - 无法以编程方式确定我的应用程序使用哪个 TLS 版本

C++ WinINet InternetReadFile 函数刷新

c++ - WinInet上传文件

c++ - 命令行参数

c++ - 通过具有多重继承的类向上转换 nullptr

c++ - 在自身内部定义类的标准实例 (C++)

c++ - STM32 LWIP PPPos 实现

python - 如何在 python 中使用 ctypes.windll.Wininet.InternetQueryOptionW

c++ - 无法使用 wininet 将 ZIP 文件发布到服务器