I try to get a JSON from a REST API (blocking is fine for now) using boost::asio::read. The problem I have is that I don't know how to deal if the response consists of multiple ethernet frames. When this is the case and I print the JSON, between the frames there is some "rubbish", I don't know if it is padding or some headers. How do I solve this? How can I know until when I have to read and from where I need to read again? Thanks.
uint16_t port = 80; //TLS later?
std::string address = this->hostip_ + ":" + std::to_string(port);
//resolve address
boost::asio::ip::tcp::resolver resolver(io_service);
boost::asio::ip::tcp::resolver::query query(hostip_, std::to_string(port));
boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
//create socket
boost::asio::ip::tcp::socket socket(io_service);
try
{
boost::asio::connect(socket, endpoint_iterator);
}
catch (const std::exception& e)
{
std::cout << "Could not connect to API host";
return false;
}
//form the request
std::string hostAddress = hostip_ + ":" + std::to_string(port);
boost::asio::streambuf request;
std::ostream request_stream(&request);
request_stream << "GET " << restURI_ << " HTTP/1.1\r\n";
request_stream << "Host: " << hostAddress << "\r\n";
request_stream << "Accept: */*\r\n";
request_stream << "Connection: close\r\n\r\n";
//send the request
boost::asio::write(socket, request);
//read the full response
boost::asio::streambuf response;
boost::system::error_code error;
while (boost::asio::read(socket, response,boost::asio::transfer_at_least(1), error));
//convert to string
boost::asio::streambuf::const_buffers_type buf = response.data();
const std::string bufferstr(boost::asio::buffers_begin(buf), boost::asio::buffers_begin(buf) + response.size());
仅使用 C++11 和 Boost.Asio 即可使用Boost.Beast 、Portable HTTP、WebSocket 和网络操作!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.