[英]Access REST API as client in c++ with boost, ethernet framing issue
I try to get a JSON from a REST API (blocking is fine for now) using boost::asio::read.我尝试使用 boost::asio::read 从 REST API 获取 JSON(现在阻塞很好)。 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.
在这种情况下,我打印 JSON 时,帧之间有一些“垃圾”,我不知道它是填充还是一些标题。 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 和网络操作!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.