繁体   English   中英

如何使用Poco C ++从HTTP服务器响应中读取图像内容?

[英]How to read image content from an HTTP server response using Poco C++?

我正在使用Poco在C ++中编写HTTP客户端,并且存在服务器发送带有jpeg图像内容(以字节为单位)的响应的情况。 我需要客户端处理响应并从这些字节生成jpg图像文件。

我在Poco图书馆搜索了相应的功能,但我还没找到。 似乎唯一的方法是手动完成。

这是我的代码的一部分。 它接受响应并使输入流从图像内容的开头开始。

    /* Get response */
    HTTPResponse res;
    cout << res.getStatus() << " " << res.getReason() << endl;

    istream &is = session.receiveResponse(res);

    /* Download the image from the server */
    char *s = NULL;
    int length;
    std::string slength;

    for (;;) {
        is.getline(s, '\n');
        string line(s);

        if (line.find("Content-Length:") < 0)
            continue;

        slength = line.substr(15);
        slength = trim(slength);
        stringstream(slength) >> length;

        break;
    }

    /* Make `is` point to the beginning of the image content */
    is.getline(s, '\n');

如何进行?

下面是将响应主体作为字符串获取的代码。 您也可以将它直接写入带有ofstream的文件(见下文)。

    #include <iostream>
    #include <sstream>
    #include <string>

    #include <Poco/Net/HTTPClientSession.h>
    #include <Poco/Net/HTTPRequest.h>
    #include <Poco/Net/HTTPResponse.h>
    #include <Poco/Net/Context.h>
    #include <Poco/Net/SSLManager.h>
    #include <Poco/StreamCopier.h>
    #include <Poco/Path.h>
    #include <Poco/URI.h>
    #include <Poco/Exception.h>


    ostringstream out_string_stream;

    // send request
    HTTPRequest request( HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1 );
    session.sendRequest( request );

    // get response
    HTTPResponse response;
    cout << response.getStatus() << " " << response.getReason() << endl;

    // print response
    istream &is = session.receiveResponse( response );
    StreamCopier::copyStream( is, out_string_stream );

    string response_body = out_string_stream.str();

要直接写入文件,您可以使用:

    // print response
    istream &is = session->receiveResponse( response );

    ofstream outfile;
    outfile.open( "myfile.jpg" );

    StreamCopier::copyStream( is, outfile );

    outfile.close();

不要重新发明轮子。 正确地做HTTP很难。 使用现有的库,例如libcurl。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM