danicoin/src/Rpc/HttpClient.h

85 lines
2.4 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/>.
#pragma once
#include <memory>
#include <HTTP/HttpRequest.h>
#include <HTTP/HttpResponse.h>
#include <System/TcpConnection.h>
#include <System/TcpStream.h>
2015-07-30 15:22:07 +00:00
#include "Serialization/SerializationTools.h"
2015-05-27 12:08:46 +00:00
namespace CryptoNote {
class HttpClient {
public:
HttpClient(System::Dispatcher& dispatcher, const std::string& address, uint16_t port);
2015-07-30 15:22:07 +00:00
~HttpClient();
2015-05-27 12:08:46 +00:00
void request(const HttpRequest& req, HttpResponse& res);
private:
void connect();
void disconnect();
const std::string m_address;
const uint16_t m_port;
bool m_connected = false;
System::Dispatcher& m_dispatcher;
System::TcpConnection m_connection;
std::unique_ptr<System::TcpStreambuf> m_streamBuf;
};
template <typename Request, typename Response>
void invokeJsonCommand(HttpClient& client, const std::string& url, const Request& req, Response& res) {
HttpRequest hreq;
HttpResponse hres;
hreq.setUrl(url);
2015-07-15 12:23:00 +00:00
hreq.setBody(storeToJson(req));
2015-05-27 12:08:46 +00:00
client.request(hreq, hres);
if (hres.getStatus() != HttpResponse::STATUS_200) {
throw std::runtime_error("HTTP status: " + std::to_string(hres.getStatus()));
}
2015-07-15 12:23:00 +00:00
if (!loadFromJson(res, hres.getBody())) {
2015-05-27 12:08:46 +00:00
throw std::runtime_error("Failed to parse JSON response");
}
}
template <typename Request, typename Response>
void invokeBinaryCommand(HttpClient& client, const std::string& url, const Request& req, Response& res) {
HttpRequest hreq;
HttpResponse hres;
hreq.setUrl(url);
2015-07-15 12:23:00 +00:00
hreq.setBody(storeToBinaryKeyValue(req));
2015-05-27 12:08:46 +00:00
client.request(hreq, hres);
2015-07-15 12:23:00 +00:00
if (!loadFromBinaryKeyValue(res, hres.getBody())) {
2015-05-27 12:08:46 +00:00
throw std::runtime_error("Failed to parse binary response");
}
}
}