使用 boost::beast 处理大型 http 响应

佐哈尔81

以下代码用于获取http响应消息:

  boost::beast::tcp_stream stream_;

  boost::beast::flat_buffer buffer;
  boost::beast::http::response<boost::beast::http::dynamic_body> res;
  boost::beast::http::read(stream_, buffer, res);

但是,在某些情况下,根据前面的请求,我可以预期响应消息正文将包含大型二进制文件。

因此,我想直接将它读到文件系统而不是通过buffer变量来避免过度使用进程内存。怎么做到呢 ?

在 Objective-c 框架中,NSUrlSession有一种简单的方法可以使用NSURLSessionDownloadTask代替NSURLSessionDataTask,所以我想知道它是否也存在于 boost 中。

谢谢 !

您可以使用http::buffer_body.

它的文档/示例在这里https://www.boost.org/doc/libs/1_77_0/libs/beast/doc/html/beast/using_http/parser_stream_operations/incremental_read.html

重点是使用read_headerwithresponse_parser<>而不是response<>直接使用。文档示例展示了如何读取响应/请求:

/*  This function reads a message using a fixed size buffer to hold
    portions of the body, and prints the body contents to a `std::ostream`.
*/
template<
    bool isRequest,
    class SyncReadStream,
    class DynamicBuffer>
void
read_and_print_body(
    std::ostream& os,
    SyncReadStream& stream,
    DynamicBuffer& buffer,
    error_code& ec)
{
    parser<isRequest, buffer_body> p;
    read_header(stream, buffer, p, ec);
    if(ec)
        return;
    while(! p.is_done())
    {
        char buf[512];
        p.get().body().data = buf;
        p.get().body().size = sizeof(buf);
        read(stream, buffer, p, ec);
        if(ec == error::need_buffer)
            ec = {};
        if(ec)
            return;
        os.write(buf, sizeof(buf) - p.get().body().size);
    }
}

我在这里有一个高级示例:How to read data from Internet using multi-threading with only once? .

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用boost :: beast的流HTTP的异步处理

如何使用boost :: beast,下载文件无阻塞且带有响应

如何使用boost / beast从HTTP POST请求中解析和提取有效载荷?

通过SSL(HTTPS)使用Boost-Beast(Asio)http客户端

C ++ Boost 1.66使用Beast http请求解析器解析字符串

Boost Beast:当内容长度不可用时,如何使用自定义主体产生非块状响应?

Boost野兽在接受期间处理http响应头

如何处理大型 http JSON 响应正文

boost :: beast同步HTTP客户端超时

如何从 std::string 构造 boost::beast::http::message?

Boost.beast http :: read()返回“错误版本”

包含 boost/beast/http.hpp 时出现多个错误

boost.beast : HTTP/1.1 400 错误请求

使用Scala处理HTTP响应的最佳实践

使用带有Boost Beast的lambda代替绑定

如何使用boost :: beast连续流式传输文件

如何在boost-beast http请求中设置http标头?

如何使用Beast C ++库从HTTP重定向到HTTPS?

从http流(在boost :: beast中)进行读写有什么要求?

带Boost :: Beast的SSL隧道

在html中使用ajax处理HTTP Get响应

无法在Siddhi中使用'regex'http状态代码处理响应

使用AsyncTask时应如何处理HTTP响应代码?

使用CFTHREAD处理外部HTTP请求并返回异步响应

AngularJS HTTP 使用响应

无法使用 HTTP 响应

我想使用 nlohmann:json 解析带有 msgpack 数据的 boost::beast::flat_buffer

使用 Boost Beast 在 SSL 连接中构建特定于平台的客户端身份验证

使用boost :: beast解码Ntrip 1.0协议的最佳方法是什么