2 // Copyright (c) 2016-2017 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 using tcp
= boost::asio::ip::tcp
; // from <boost/asio/ip/tcp.hpp>
28 namespace http
= boost::beast::http
; // from <boost/beast/http.hpp>
30 // Performs an HTTP GET and prints the response
31 int main(int argc
, char** argv
)
35 // Check command line arguments.
36 if(argc
!= 4 && argc
!= 5)
39 "Usage: http-client-sync <host> <port> <target> [<HTTP version: 1.0 or 1.1(default)>]\n" <<
41 " http-client-sync www.example.com 80 /\n" <<
42 " http-client-sync www.example.com 80 / 1.0\n";
45 auto const host
= argv
[1];
46 auto const port
= argv
[2];
47 auto const target
= argv
[3];
48 int version
= argc
== 5 && !std::strcmp("1.0", argv
[4]) ? 10 : 11;
50 // The io_context is required for all I/O
51 boost::asio::io_context ioc
;
53 // These objects perform our I/O
54 tcp::resolver resolver
{ioc
};
55 tcp::socket socket
{ioc
};
57 // Look up the domain name
58 auto const results
= resolver
.resolve(host
, port
);
60 // Make the connection on the IP address we get from a lookup
61 boost::asio::connect(socket
, results
.begin(), results
.end());
63 // Set up an HTTP GET request message
64 http::request
<http::string_body
> req
{http::verb::get
, target
, version
};
65 req
.set(http::field::host
, host
);
66 req
.set(http::field::user_agent
, BOOST_BEAST_VERSION_STRING
);
68 // Send the HTTP request to the remote host
69 http::write(socket
, req
);
71 // This buffer is used for reading and must be persisted
72 boost::beast::flat_buffer buffer
;
74 // Declare a container to hold the response
75 http::response
<http::dynamic_body
> res
;
77 // Receive the HTTP response
78 http::read(socket
, buffer
, res
);
80 // Write the message to standard out
81 std::cout
<< res
<< std::endl
;
83 // Gracefully close the socket
84 boost::system::error_code ec
;
85 socket
.shutdown(tcp::socket::shutdown_both
, ec
);
87 // not_connected happens sometimes
88 // so don't bother reporting it.
90 if(ec
&& ec
!= boost::system::errc::not_connected
)
91 throw boost::system::system_error
{ec
};
93 // If we get here then the connection is closed gracefully
95 catch(std::exception
const& e
)
97 std::cerr
<< "Error: " << e
.what() << std::endl
;