C++ Send data in body with Boost.asio and Beast library
Asked Answered
U

2

10

I've to use a C++ library for sending data to a REST-Webservice of our company. I start with Boost and Beast and with the example given here under Code::Blocks in a Ubuntu 16.04 enviroment. 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.

But how can I set data inside the request (req) from this definition:

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

I tried to use some 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.

Google doesn't show new example about this, only the above code is found as a example.

Someone with a hint to a code example or using about the Beast (roar). Or should I use websockets? Or only boost::asio like answered here?

Thanks in advance and excuse my bad english.

Unsavory answered 2/6, 2017 at 14:25 Comment(0)
D
13

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:

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";
Discommend answered 17/7, 2017 at 12:14 Comment(0)
B
15

Small addition to Eliott Paris's answer:

  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.

Boccioni answered 27/10, 2017 at 20:36 Comment(1)
Please let me know how to print the payload before sending it (writing to socket) using ostringstream and whether we need to add \r\n at the end of each line how we do it in boost asio http call?Renell
D
13

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:

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";
Discommend answered 17/7, 2017 at 12:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.