HTTP客户端
使用HTTP向网站发出GET请求并打印响应:
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <cstdlib>
#include <iostream>
#include <string>
using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
namespace http = boost::beast::http; // from <boost/beast/http.hpp>
// Performs an HTTP GET and prints the response
//执行HTTP获取并打印响应
int main(int argc, char** argv)
{
try
{
//http://127.0.0.1:9580/engine/api/anchor/get_anchor
auto const host = "127.0.0.1";
auto const port = "9580";
auto const target = "/engine/api/anchor/get_anchor";
int version = 11;
// The io_context is required for all I/O
// IO上下文对于所有I/O都是必需的
boost::asio::io_context ioc;
// These objects perform our I/O
// 这些对象执行我们的输入输出。
tcp::resolver resolver{ioc};
tcp::socket socket{ioc};
// Look up the domain name
// 查找域名
auto const results = resolver.resolve(host, port);
// Make the connection on the IP address we get from a lookup
// 从查找得到的IP地址上进行连接
boost::asio::connect(socket, results.begin(), results.end());
// Set up an HTTP GET request message
// 设置HTTP GET请求消息
http::request<http::string_body> req{http::verb::get, target,version};
req.set(http::field::host, host);
req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
// Send the HTTP request to the remote host
// 向远程主机发送HTTP请求
http::write(socket, req);
// This buffer is used for reading and must be persisted
// 此缓冲器用于读取,并且必须持久化。
boost::beast::flat_buffer buffer;
// Declare a container to hold the response
// 声明容器以保存响应
http::response<http::dynamic_body> res;
// Receive the HTTP response
// 接收HTTP响应
http::read(socket, buffer, res);
// Write the message to standard out
// 将消息写入标准输出
/* std::cout << ss << std::endl;*/
//将获得的数据转换成字符串
std::stringstream ss;
ss <<boost::beast::buffers(res.body().data());
std::string body = ss.str();
// Gracefully close the socket
// 关闭套接字
boost::system::error_code ec;
socket.shutdown(tcp::socket::shutdown_both, ec);
// not_connected happens sometimes
//有时会发生not_connected
// so don't bother reporting it.
//所以不要费心去报道。
if(ec && ec != boost::system::errc::not_connected)
throw boost::system::system_error{ec};
// If we get here then the connection is closed gracefully
// 如果我们到达这里,连接就被关闭了。
}
catch(std::exception const& e)
{
std::cerr << "Error: " << e.what() << std::endl;
return EXIT_FAILURE;
}
system("pause");
return EXIT_SUCCESS;
}