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 回答