4

I am trying to send message with a header using boost http library. I searched for a way to send message with a header but I could not find.

what I want to do is following

auto const results = resolver.resolve(host, port);
beast::get_lowest_layer(stream).connect(results);
stream.handshake(ssl::stream_base::client);

http::request<http::string_body> req(verb, query + data, 11);
req.set(http::field::host, host);
// set http header ("key" = "I am a header")
// I want to add above code.
req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);

http::write(stream, req);
beast::flat_buffer buffer;
http::response<http::dynamic_body> res;
http::read(stream, buffer, res);

Please let me know proper way to add header to boost-beast http request. Thanks!

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
wwwwe
  • 127
  • 1
  • 7

1 Answers1

7

Just

req.set("key", "I am a header");

It's pretty much the same as the other - standard HTTP - header, but using a custom name.

See it Live On Coliru

#include <boost/beast/http.hpp>
#include <iostream>
namespace http = boost::beast::http;

int main() {
    auto verb = http::verb::get;
    std::string query = "/path";
    std::string data = "?whatever=more";
    std::string host = "example.com";

    http::request<http::string_body> req(verb, query + data, 11);
    req.set(http::field::host, host);
    req.set("key", "I am a header");
    req.prepare_payload();

    std::cout << req;
}

Prints

GET /path?whatever=more HTTP/1.1
Host: example.com
key: I am a header
sehe
  • 374,641
  • 47
  • 450
  • 633