0

I've been using Boost.Beast for awhile now to send HTTP requests and I think it's great and works perfectly. But does anyone know if it's possible to construct an HTTP batch request using Beast? I'm thinking something like creating several subrequests:

boost::beast::http::request<boost::beast::http::string_body> subrequest_1;

subrequest_1.set(boost::beast::http::field::content_type, "application/http");

...

boost::beast::http::request<boost::beast::http::string_body> subrequest_2;

subrequest_2.set(boost::beast::http::field::content_type, "application/http");

...

and then somehow group them together and send them all in one request.

I've been trying to create a vector, add the subrequests to it and then assign the vector to the body of the request I'd like to send, but that hasn't been successful.

/*

std::vector<boost::beast::http::request<boost::beast::http::string_body>> v;
v.push_back(subrequest_1);

v.push_back(subrequest_2);

boost::beast::http::request<boost::beast::http::string_body> request;

request.method(boost::beast::http::verb::post);
...
request.body() = v;   
*/

Thanks in advance!

Marek R
  • 32,568
  • 6
  • 55
  • 140
filbri
  • 1
  • 1

1 Answers1

0

Well this one turned out to be very simple. I'll just post my solution here in case anyone else feels as lost as I did a couple of days ago.

    // Set up the request with a new content type
    boost::beast::http::request<boost::beast::http::string_body> request;
    request.set(field::content_type, "multipart/mixed; boundary='subrequest_boundary'");

    // A string to hold the entire batch request
    std::string body;

    // Add all messages in e.g. a queue to the string
    while ( messages.size() )
    {
        auto message = messages.front();

        // Add a boundary to separate the messages
        body.append("--subrequest_boundary");
        body.append("Content-Type: application/http\n");
        /*
        And all more headers you need
        */

        // I used the nlohmann library to add json docs
        nlohmann::json payload =    {
                                        {"message",
                                        }
                                    };
        body.append( payload.dump() );
        messages.pop();
    }
    // Add a boundary as wrap up
    body.append("--subrequest_boundary--");

    // Add the batch request to the request
    request.body() = body;
    request.prepare_payload();
filbri
  • 1
  • 1