首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Poco C++从HTTP服务器响应中读取图片内容?

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

Stack Overflow用户
提问于 2012-01-14 22:21:45
回答 2查看 5.9K关注 0票数 4

我正在用Poco用C++编写一个超文本传输协议客户端,在这种情况下,服务器会发送一个带有jpeg图像内容(以字节为单位)的响应。我需要客户端处理响应,并从这些字节生成一个jpg图像文件。

我在Poco库中搜索了合适的函数,但没有找到。看起来唯一的方法就是手动完成。

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

代码语言:javascript
复制
    /* 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');

如何继续?

EN

回答 2

Stack Overflow用户

发布于 2012-07-25 02:45:25

下面是以字符串形式获取响应体的代码。你也可以用ofstream把它直接写到一个文件中(见下文)。

代码语言:javascript
复制
    #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();

要直接写入文件,可以使用以下命令:

代码语言:javascript
复制
    // print response
    istream &is = session->receiveResponse( response );

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

    StreamCopier::copyStream( is, outfile );

    outfile.close();
票数 3
EN

Stack Overflow用户

发布于 2012-01-14 23:41:00

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

票数 -9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8862772

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档