C++使用Boost.asio和Beast库发送数据

Ban*_*zai 9 c++ rest boost boost-beast

我将使用C++库将数据发送到我们公司的REST-Web服务.我开始升压和野兽与给出的例子在这里代码:: Blocks的下一个Ubuntu的16.04环境.该文档没有帮助我解决以下问题:

我的代码或多或少等于示例,我可以成功编译并向我的测试Web服务发送GET请求.

但是如何在此定义中的请求(req)中设置数据:

:
beast::http::request<beast::http::string_body> req;
req.method("GET");
req.target("/");
:
Run Code Online (Sandbox Code Playgroud)

我尝试使用一些req.body.???,但代码completition没有给我一个功能的提示(顺便说一句.不工作).我知道req.method必须更改为"POST"才能发送数据.

Google没有显示有关此问题的新示例,仅以上述代码为例.

有人提示代码示例或使用关于野兽(咆哮)的人.或者我应该使用websockets?或者只有boost :: asio 在这里回答?

提前谢谢,原谅我糟糕的英语.

小智 10

要根据您的请求发送数据,您需要填写正文并指定内容类型.

beast::http::request<beast::http::string_body> req;
req.method(beast::http::verb::post);
req.target("/");
Run Code Online (Sandbox Code Playgroud)

如果要将"key = value"作为"x-www-form-urlencoded"对发送:

req.set(beast::http::field::content_type, "application/x-www-form-urlencoded");
req.body() = "name=foo";
Run Code Online (Sandbox Code Playgroud)

或原始数据:

req.set(beast::http::field::content_type, "text/plain");
req.body() = "Some raw data";
Run Code Online (Sandbox Code Playgroud)


小智 9

Eliott Paris的答案很少:

  1. 设置正文的语法正确

    req.body() = "name=foo";
    
    Run Code Online (Sandbox Code Playgroud)
  2. 你应该添加

    req.prepare_payload();
    
    Run Code Online (Sandbox Code Playgroud)

    设置正文后,在HTTP标头中设置正文大小.