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

How to set up http header in boost-beast http request?

本文关键字:http 请求 设置 beast boost      更新时间:2023-10-16

我正在尝试使用boost http库发送带有标头的消息。我搜索了一种发送带有标题的消息的方法,但找不到。

我想做的是跟踪

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);

请让我知道正确的方式添加头以促进野兽http请求。谢谢

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

它与其他标准的HTTP标头几乎相同,只是使用了自定义名称。

查看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;
}

打印

GET /path?whatever=more HTTP/1.1
Host: example.com
key: I am a header