danicoin/src/rpc/HttpClient.cpp

62 lines
1.8 KiB
C++
Raw Normal View History

2015-05-27 12:08:46 +00:00
// Copyright (c) 2012-2015, The CryptoNote developers, The Bytecoin developers
//
// This file is part of Bytecoin.
//
// Bytecoin is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Bytecoin is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with Bytecoin. If not, see <http://www.gnu.org/licenses/>.
#include "HttpClient.h"
#include <HTTP/HttpParser.h>
#include <System/Ipv4Resolver.h>
#include <System/Ipv4Address.h>
#include <System/TcpConnector.h>
namespace CryptoNote {
HttpClient::HttpClient(System::Dispatcher& dispatcher, const std::string& address, uint16_t port) :
m_dispatcher(dispatcher), m_address(address), m_port(port) {
}
void HttpClient::request(const HttpRequest &req, HttpResponse &res) {
if (!m_connected) {
connect();
}
try {
std::iostream stream(m_streamBuf.get());
HttpParser parser;
stream << req;
stream.flush();
parser.receiveResponse(stream, res);
} catch (const std::exception &) {
disconnect();
throw;
}
}
void HttpClient::connect() {
auto ipAddr = System::Ipv4Resolver(m_dispatcher).resolve(m_address);
m_connection = System::TcpConnector(m_dispatcher).connect(ipAddr, m_port);
m_streamBuf.reset(new System::TcpStreambuf(m_connection));
m_connected = true;
}
void HttpClient::disconnect() {
m_streamBuf.reset();
m_connection = System::TcpConnection();
m_connected = false;
}
}