c++11 - Boost Beast HTTP

标签 c++11 visual-c++ boost boost-beast

我正在开发一个 http 解析器,看起来 boost.beast 是一个不错的解析器。但是,我仍然有一些问题:

*** 假设已经通过 boost.asio 套接字接收到 HTTP 请求 POST 数据。存储在 std::string 缓冲区内。

  • 是否有关于如何提取 http header 字段及其值(一个接一个)的好的示例?我认为这将是一个迭代器方法,但我尝试了几种方法,但仍然无法正常工作。
  • 如何提取http正文?

  • 非常感谢。

    最佳答案

    从一个简单的例子开始:https://www.boost.org/doc/libs/develop/libs/beast/example/http/client/sync/http_client_sync.cpp

        // Declare a container to hold the response
        http::response<http::dynamic_body> res;
    
        // Receive the HTTP response
        http::read(socket, buffer, res);
    

    提取标题

    响应对象已经包含所有商品:
    for(auto const& field : res)
        std::cout << field.name() << " = " << field.value() << "\n";
    
    std::cout << "Server: " << res[http::field::server] << "\n";
    

    您也可以只流式传输整个响应对象:
    std::cout << res << std::endl;
    

    提取 body
    std::cout << "Body size is " << res.body().size() << "\n";
    

    要实际使用“dynamic_body”,请使用标准的 Asio 缓冲区操作:
    #include <boost/asio/buffers_iterator.hpp>
    #include <boost/asio/buffers_iterator.hpp>
    
    std::string body { boost::asio::buffers_begin(res.body().data()),
                       boost::asio::buffers_end(res.body().data()) };
    
    std::cout << "Body: " << std::quoted(body) << "\n";
    

    Alternatively, see beast::buffers_to_string



    显然,当使用 string_body 时,事情变得更简单了。 :
    std::cout << "Body: " << std::quoted(res.body()) << "\n";
    

    关于c++11 - Boost Beast HTTP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50479407/

    相关文章:

    c++ - 海湾合作委员会 "no matching function for call.."错误

    c++ - windows下使用boost::asio的udp广播

    c++ - 无序时解析逗号分隔的语法

    c++ - 类静态成员的冲突声明

    c++ - 推断 "make_function"的 lambda 或任意可调用对象的调用签名

    c++ - 稳定的时钟在系统范围内稳定吗?

    curl - 如何正确安装 libcurl 以在 Visual Studio 2017 中使用?

    windows - 如何使 Win32 对话框出现在默认位置(CW_USEDEFAULT)?

    c++ - Const 放置以停止使用 boost shared_ptr 编辑指针数据

    枚举类的 c++ typedef/type 替换