2 // Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
4 // Distributed under the Boost Software License, Version 1.0. (See accompanying
5 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
7 // Official repository: https://github.com/boostorg/beast
10 //------------------------------------------------------------------------------
12 // Example: HTTP client, synchronous
14 //------------------------------------------------------------------------------
16 //[example_http_client
18 #include <boost/beast/core.hpp>
19 #include <boost/beast/http.hpp>
20 #include <boost/beast/version.hpp>
21 #include <boost/asio/connect.hpp>
22 #include <boost/asio/ip/tcp.hpp>
27 namespace beast
= boost::beast
; // from <boost/beast.hpp>
28 namespace http
= beast::http
; // from <boost/beast/http.hpp>
29 namespace net
= boost::asio
; // from <boost/asio.hpp>
30 using tcp
= net::ip::tcp
; // from <boost/asio/ip/tcp.hpp>
32 // Performs an HTTP GET and prints the response
33 int main(int argc
, char** argv
)
37 // Check command line arguments.
38 if(argc
!= 4 && argc
!= 5)
41 "Usage: http-client-sync <host> <port> <target> [<HTTP version: 1.0 or 1.1(default)>]\n" <<
43 " http-client-sync www.example.com 80 /\n" <<
44 " http-client-sync www.example.com 80 / 1.0\n";
47 auto const host
= argv
[1];
48 auto const port
= argv
[2];
49 auto const target
= argv
[3];
50 int version
= argc
== 5 && !std::strcmp("1.0", argv
[4]) ? 10 : 11;
52 // The io_context is required for all I/O
55 // These objects perform our I/O
56 tcp::resolver
resolver(ioc
);
57 beast::tcp_stream
stream(ioc
);
59 // Look up the domain name
60 auto const results
= resolver
.resolve(host
, port
);
62 // Make the connection on the IP address we get from a lookup
63 stream
.connect(results
);
65 // Set up an HTTP GET request message
66 http::request
<http::string_body
> req
{http::verb::get
, target
, version
};
67 req
.set(http::field::host
, host
);
68 req
.set(http::field::user_agent
, BOOST_BEAST_VERSION_STRING
);
70 // Send the HTTP request to the remote host
71 http::write(stream
, req
);
73 // This buffer is used for reading and must be persisted
74 beast::flat_buffer buffer
;
76 // Declare a container to hold the response
77 http::response
<http::dynamic_body
> res
;
79 // Receive the HTTP response
80 http::read(stream
, buffer
, res
);
82 // Write the message to standard out
83 std::cout
<< res
<< std::endl
;
85 // Gracefully close the socket
87 stream
.socket().shutdown(tcp::socket::shutdown_both
, ec
);
89 // not_connected happens sometimes
90 // so don't bother reporting it.
92 if(ec
&& ec
!= beast::errc::not_connected
)
93 throw beast::system_error
{ec
};
95 // If we get here then the connection is closed gracefully
97 catch(std::exception
const& e
)
99 std::cerr
<< "Error: " << e
.what() << std::endl
;