Performs an HTTP GET and prints the response
| 31 | |
| 32 | // Performs an HTTP GET and prints the response |
| 33 | int main(int argc, char** argv) |
| 34 | { |
| 35 | try |
| 36 | { |
| 37 | // Check command line arguments. |
| 38 | if(argc != 4 && argc != 5) |
| 39 | { |
| 40 | std::cerr << |
| 41 | "Usage: http-client-sync <host> <port> <target> [<HTTP version: 1.0 or 1.1(default)>]\n" << |
| 42 | "Example:\n" << |
| 43 | " http-client-sync www.example.com 80 /\n" << |
| 44 | " http-client-sync www.example.com 80 / 1.0\n"; |
| 45 | return EXIT_FAILURE; |
| 46 | } |
| 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; |
| 51 | |
| 52 | // The io_context is required for all I/O |
| 53 | net::io_context ioc; |
| 54 | |
| 55 | // These objects perform our I/O |
| 56 | tcp::resolver resolver(ioc); |
| 57 | beast::tcp_stream stream(ioc); |
| 58 | |
| 59 | // Look up the domain name |
| 60 | auto const results = resolver.resolve(host, port); |
| 61 | |
| 62 | // Make the connection on the IP address we get from a lookup |
| 63 | stream.connect(results); |
| 64 | |
| 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); |
| 69 | |
| 70 | // Send the HTTP request to the remote host |
| 71 | http::write(stream, req); |
| 72 | |
| 73 | // This buffer is used for reading and must be persisted |
| 74 | beast::flat_buffer buffer; |
| 75 | |
| 76 | // Declare a container to hold the response |
| 77 | http::response<http::dynamic_body> res; |
| 78 | |
| 79 | // Receive the HTTP response |
| 80 | http::read(stream, buffer, res); |
| 81 | |
| 82 | // Write the message to standard out |
| 83 | std::cout << res << std::endl; |
| 84 | |
| 85 | // Gracefully close the socket |
| 86 | beast::error_code ec; |
| 87 | stream.socket().shutdown(tcp::socket::shutdown_both, ec); |
| 88 | |
| 89 | // not_connected happens sometimes |
| 90 | // so don't bother reporting it. |