以下代码用于获取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
.
重点是使用read_header
withresponse_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] 删除。
我来说两句