简体   繁体   English

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

[英]C++ Send data in body with Boost.asio and Beast library

I've to use a C++ library for sending data to a REST-Webservice of our company. 我将使用C ++库将数据发送到我们公司的REST-Web服务。 I start with Boost and Beast and with the example given here under Code::Blocks in a Ubuntu 16.04 enviroment. 我开始升压和野兽与给出的例子在这里代码:: Blocks的下一个Ubuntu的16.04环境。 The documentation doesn't helped me in following problem: 该文档没有帮助我解决以下问题:

My code is, more or less, equal to the example and I can compile and send a GET-request to my test webservice successfully. 我的代码或多或少等于示例,我可以成功编译并向我的测试Web服务发送GET请求。

But how can I set data inside the request (req) from this definition: 但是如何在此定义中的请求(req)中设置数据:

:
beast::http::request<beast::http::string_body> req;
req.method("GET");
req.target("/");
:

I tried to use some req.body.??? 我试着用一些req.body.??? , but code completition doesn't give me a hint about functionality (btw. don't work). ,但代码完整性并没有给我一些关于功能的提示(顺便说一句。不行)。 I know that req.method must be changed to "POST" to send data. 我知道必须将req.method更改为“POST”才能发送数据。

Google doesn't show new example about this, only the above code is found as a example. Google没有显示有关此问题的新示例,仅以上述代码为例。

Someone with a hint to a code example or using about the Beast ( roar ). 有人提示代码示例或使用关于野兽( 咆哮 )的人。 Or should I use websockets? 或者我应该使用websockets? Or only boost::asio like answered here ? 或者只有boost :: asio 在这里回答?

Thanks in advance and excuse my bad english. 提前谢谢,原谅我糟糕的英语。

To send data with your request you'll need to fill the body and specify the content type. 要根据您的请求发送数据,您需要填写正文并指定内容类型。

beast::http::request<beast::http::string_body> req;
req.method(beast::http::verb::post);
req.target("/");

If you want to send "key=value" as a "x-www-form-urlencoded" pair: 如果要将“key = value”作为“x-www-form-urlencoded”对发送:

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

Or raw data: 或原始数据:

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

Small addition to Eliott Paris's answer: Eliott Paris的答案很少:

  1. Correct syntax for setting body is 设置正文的语法正确

     req.body() = "name=foo"; 
  2. You should add 你应该添加

     req.prepare_payload(); 

    after setting the body to set body size in HTTP headers. 设置正文后,在HTTP标头中设置正文大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM