Skip to content

Commit

Permalink
[util] Add method http_get
Browse files Browse the repository at this point in the history
  • Loading branch information
dagurval committed Mar 26, 2019
1 parent 3ea052b commit 8dff940
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/.formatted-files
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,8 @@ unlimited.cpp
unlimited.h
util.cpp
util.h
utilhttp.cpp
utilhttp.h
utilmoneystr.cpp
utilmoneystr.h
utilstrencodings.cpp
Expand Down
2 changes: 2 additions & 0 deletions src/Makefile.am
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,7 @@ BITCOIN_CORE_H = \
ui_interface.h \
undo.h \
unlimited.h \
utilhttp.h \
stat.h \
tweak.h \
requestManager.h \
Expand Down Expand Up @@ -291,6 +292,7 @@ libbitcoin_server_a_SOURCES = \
txorphanpool.cpp \
tweak.cpp \
unlimited.cpp \
utilhttp.cpp \
requestManager.cpp \
validation/forks.cpp \
validation/validation.cpp \
Expand Down
52 changes: 52 additions & 0 deletions src/utilhttp.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#include "utilhttp.h"
#include "util.h"

#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <stdexcept>

using tcp = boost::asio::ip::tcp;
namespace http = boost::beast::http;

std::stringstream http_get(const std::string &host,
const std::string &service, /* aka port number */
const std::string &target)
{
boost::asio::io_context ioc;
tcp::resolver resolver{ioc};
tcp::socket socket{ioc};

// resolve host
auto const results = resolver.resolve(host, service);

// send request
boost::asio::connect(socket, results.begin(), results.end());
int version = 11; // HTTP 1.1
http::request<http::string_body> req{http::verb::get, target, version};
req.set(http::field::host, host);
req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
http::write(socket, req);

// read response
boost::beast::flat_buffer buffer;
http::response<http::dynamic_body> res;
http::read(socket, buffer, res);
std::stringstream ss;
ss << res;

// close connection
boost::system::error_code ec;
socket.shutdown(tcp::socket::shutdown_both, ec);

// not_connected is supposedly ok to ignore
if (ec && ec != boost::system::errc::not_connected)
throw std::runtime_error(ec.message());

return ss;
}
11 changes: 11 additions & 0 deletions src/utilhttp.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#ifndef UTILHTTP_H
#define UTILHTTP_H

#include <sstream>
#include <string>

std::stringstream http_get(const std::string &host,
const std::string &service /* aka port */,
const std::string &target /* ex: /index.html */);

#endif

0 comments on commit 8dff940

Please sign in to comment.