Files
beast/example/http-client/http_client.cpp

93 lines
2.4 KiB
C++
Raw Normal View History

2017-07-20 08:01:46 -07:00
//
2017-02-06 20:07:03 -05:00
// Copyright (c) 2013-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
2017-07-20 08:01:46 -07:00
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
//[example_http_client
2017-06-04 17:25:55 -07:00
#include <beast/core.hpp>
2017-07-20 08:01:46 -07:00
#include <beast/http.hpp>
2017-06-21 04:38:42 -07:00
#include <beast/version.hpp>
2017-07-20 08:01:46 -07:00
#include <boost/asio.hpp>
#include <cstdlib>
2017-07-20 08:01:46 -07:00
#include <iostream>
#include <string>
2017-06-19 14:41:28 -07:00
using tcp = boost::asio::ip::tcp; // from <boost/asio.hpp>
namespace http = beast::http; // from <beast/http.hpp>
2017-07-20 08:01:46 -07:00
int main()
{
// A helper for reporting errors
auto const fail =
[](std::string what, beast::error_code ec)
{
std::cerr << what << ": " << ec.message() << std::endl;
std::cerr.flush();
return EXIT_FAILURE;
};
2017-06-18 18:44:28 -07:00
beast::error_code ec;
// Set up an asio socket
2017-07-20 08:01:46 -07:00
boost::asio::io_service ios;
2017-06-19 14:41:28 -07:00
tcp::resolver r{ios};
tcp::socket sock{ios};
2017-07-20 08:01:46 -07:00
// Look up the domain name
std::string const host = "www.example.com";
2017-06-19 07:28:20 -07:00
auto const lookup = r.resolve({host, "http"}, ec);
if(ec)
return fail("resolve", ec);
// Make the connection on the IP address we get from a lookup
boost::asio::connect(sock, lookup, ec);
if(ec)
return fail("connect", ec);
// Set up an HTTP GET request message
2017-06-19 14:41:28 -07:00
http::request<http::string_body> req;
req.method(http::verb::get);
req.target("/");
req.version = 11;
2017-06-19 14:41:28 -07:00
req.set(http::field::host, host + ":" +
std::to_string(sock.remote_endpoint().port()));
2017-06-21 04:38:42 -07:00
req.set(http::field::user_agent, BEAST_VERSION_STRING);
req.prepare_payload();
2017-07-20 08:01:46 -07:00
// Write the HTTP request to the remote host
2017-06-19 14:41:28 -07:00
http::write(sock, req, ec);
if(ec)
return fail("write", ec);
// This buffer is used for reading and must be persisted
beast::flat_buffer b;
// Declare a container to hold the response
2017-06-19 14:41:28 -07:00
http::response<http::dynamic_body> res;
// Read the response
2017-06-19 14:41:28 -07:00
http::read(sock, b, res, ec);
if(ec)
return fail("read", ec);
// Write the message to standard out
std::cout << res << std::endl;
// Gracefully close the socket
2017-06-19 14:41:28 -07:00
sock.shutdown(tcp::socket::shutdown_both, ec);
2017-06-19 19:42:06 -07:00
// not_connected happens sometimes
// so don't bother reporting it.
//
if(ec && ec != beast::errc::not_connected)
return fail("shutdown", ec);
// If we get here then the connection is closed gracefully
return EXIT_SUCCESS;
2017-07-20 08:01:46 -07:00
}
2017-06-04 17:25:55 -07:00
//]