Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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.

like image 515
Banzai Avatar asked Jun 02 '17 14:06

Banzai


2 Answers

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";
like image 111
Eliott Paris Avatar answered Sep 30 '22 13:09

Eliott Paris


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.

like image 30
jahr Avatar answered Sep 30 '22 13:09

jahr