0

I want to parse a response with boost beast.

In my program I receive the response with cpp-httplib and then I try to parse it with boost beast for the further processing. However, I am not quite sure how to parse the response correctly.

Even after reading the boost beast documentation and posts on stackoverflow I have my issues. The last I used for orientation is: How to construct a boost::beast::http::message from std::string?

I must have messed up the lenght of the response. My code throws a message for every response received. :

partial message [beast.http:2]

Here is my code:

int request(httplib::Client &client1, string &bodyContent,    const string target, http::response<http::dynamic_body>  &myres, 
                        std::map<http::field, string> extraField)
{
    httplib::Headers reqHeader;

    // adding extra fields
    if (!extraField.empty())
    {
        for (auto const& el : extraField)
        {

            reqHeader.emplace(http::to_string(el.first), el.second);
        }
    }

    auto res1 = client1.Get(target, reqHeader);
    if (res1->status) {
        bodyContent = res1->body;
        string headerNew ;
        if (!res1->headers.empty())
        {
            httplib::Headers hIn = res1->headers;
            for (auto const& el : hIn)
            {
                headerNew += el.first + ": " + el.second+"\r\n";
            }
        }

        string httpBegin = "HTTP/1.1 " + std::to_string (res1->status);
        string newResponse = httpBegin+ " \r\n" + headerNew+ "\r\n" + res1->body;

        beast::error_code ec;
        http::response_parser<http::dynamic_body> p;

        auto buf = boost::asio::buffer(newResponse);
        auto n   = p.put(buf, ec);
        assert(p.is_header_done());

        if (!ec) {

            p.put_eof(ec);
        }
        if (ec)
            throw boost::system::system_error(ec);
        assert(p.is_done());

        p.release();
    }

    return EXIT_SUCCESS;
}
haapoo
  • 109
  • 2
  • 9
  • What is the reason for parsing something already parsed by httplib? In other words, why use httplib, or beast? – sehe Aug 22 '23 at 21:17
  • @sehe At first I was using beast. However, I had a problem with disconnections when package loss happened. For me it was too complex for the simple job. When I tested httplib I was sattisfied with the result and therefore wanted to change my "backend". – haapoo Aug 28 '23 at 06:54
  • Then I suggest you do that, instead of trying to hold on to both halves. You're complicating things for no reason. Also, network failure happen regardless of the library. Packet loss doesn't normally affect TCP: https://en.wikipedia.org/wiki/Packet_loss#:~:text=The%20Transmission%20Control%20Protocol%20(TCP,reduced%20throughput%20for%20the%20connection. so the failure likely had other causes. I'm not a httplib user, but I can review your beast code if you want – sehe Aug 28 '23 at 11:04

0 Answers0