I create http::response<string_body> and call prepare_payload() after the response is built like this
http::response<http::string_body> res;
res.version(11);
res.result(http::status::ok);
res.set(http::field::server, "Example-Server");
res.body() = "test";
// Chunked transfer encoding
res.chunked(true);
std::cout << res;
res.prepare_payload();
std::cout << res;
After calling res.prepare_payload() for some reason the Transfer-Encoding: chunked header is removed and replaced with Content-Length: 4 header:
Before prepare_payload():
HTTP/1.1 200 OK
Server: Example-Server
Transfer-Encoding: chunked
4 test
0
After prepare_payload()
HTTP/1.1 200 OK
Server: Example-Server
Content-Length: 4
test
Why is the Transfer-Encoding header replaced with Content-Length after calling res.prepare_payload() and should res.prepare_payload() be called in case of chunked responses?
Beast is opinionated and avoids chunked encoding if the content length is known ahead of time.
Prepare-payload asks Beast to do what it thinks best, depending on the type of body, http version, status-code and content length if known.
You can easily force chunked encoding if you insist, by simply re-ordering your instructions:
#include <boost/beast.hpp>
#include <iostream>
namespace http = boost::beast::http;
int main() {
http::response<http::string_body> res;
res.version(11);
res.result(http::status::ok);
res.set(http::field::server, "Example-Server");
res.body() = "test";
res.prepare_payload();
// Chunked transfer encoding
res.chunked(true);
std::cout << res;
}
Printing Live On Coliru
Server: Example-Server
Transfer-Encoding: chunked
4
test
0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With