4

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');

どうやって進める?

4

2 に答える 2

3

以下は、応答本文を文字列として取得するコードです。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();
于 2012-07-24T18:45:25.360 に答える
-9

車輪を再発明しないでください。HTTP を適切に行うのは困難です。libcurl などの既存のライブラリを使用します。

于 2012-01-14T15:41:00.340 に答える