16 #include <boost/beast/core.hpp>
17 #include <boost/beast/http.hpp>
18 #include <boost/beast/version.hpp>
19 #include <boost/asio/strand.hpp>
26 namespace beast = boost::beast;
27 namespace http = beast::http;
28 namespace net = boost::asio;
35 fail(beast::error_code ec,
char const* what)
37 std::cerr << what <<
": " << ec.message() <<
"\n";
41 class session :
public std::enable_shared_from_this<session>
46 http::request<http::empty_body>
req_;
47 http::response<http::string_body>
res_;
55 ,
stream_(net::make_strand(ioc))
68 req_.version(version);
71 req_.set(http::field::host, host);
72 req_.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
78 beast::bind_front_handler(
86 tcp::resolver::results_type results)
89 return fail(ec,
"resolve");
92 stream_.expires_after(std::chrono::seconds(30));
97 beast::bind_front_handler(
103 on_connect(beast::error_code ec, tcp::resolver::results_type::endpoint_type)
106 return fail(ec,
"connect");
109 stream_.expires_after(std::chrono::seconds(30));
113 beast::bind_front_handler(
115 shared_from_this()));
120 beast::error_code ec,
121 std::size_t bytes_transferred)
123 boost::ignore_unused(bytes_transferred);
126 return fail(ec,
"write");
130 beast::bind_front_handler(
132 shared_from_this()));
137 beast::error_code ec,
138 std::size_t bytes_transferred)
140 boost::ignore_unused(bytes_transferred);
143 return fail(ec,
"read");
146 std::cout <<
res_ << std::endl;
149 stream_.socket().shutdown(tcp::socket::shutdown_both, ec);
152 if(ec && ec != beast::errc::not_connected)
153 return fail(ec,
"shutdown");
161 int main(
int argc,
char** argv)
164 if(argc != 4 && argc != 5)
167 "Usage: http-client-async <host> <port> <target> [<HTTP version: 1.0 or 1.1(default)>]\n" <<
169 " http-client-async www.example.com 80 /\n" <<
170 " http-client-async www.example.com 80 / 1.0\n";
173 auto const host = argv[1];
174 auto const port = argv[2];
175 auto const target = argv[3];
176 int version = argc == 5 && !std::strcmp(
"1.0", argv[4]) ? 10 : 11;
182 std::make_shared<session>(ioc)->run(host, port,
target, version);