簡體   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