c++ - 如何在 boost-beast http 请求中设置 http header ?

标签 c++ http boost boost-beast

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

我想做的就是跟随

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

请告诉我将 header 添加到 boost-beast http 请求的正确方法。谢谢!

最佳答案

只是

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

它与其他 - 标准 HTTP - header 几乎相同,但使用自定义名称。

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

打印

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

关于c++ - 如何在 boost-beast http 请求中设置 http header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62845890/

相关文章:

http - 分块传输编码 - 浏览器行为

http - Web 浏览器并行下载与流水线

c++ - 可变Qt Canvas 的最佳方式

c++ - 使用 gdb 和 codelite 调试 C++ 中的无限循环

c++ - 从文件中读取类对象c++

http - YouTube 是否使用 FTP 上传?

c++ - 如何将字符串转换为目录?在 Linux 上 boost

c++ - 如何解析末尾带有可选分隔符的列表?

c++ - 编译器提示模板参数的数量错误,即使它在 boost 库文件中是正确的

c# - 如何从 C++ tesseract 库创建 C# 包装器类?