Skip to content

Instantly share code, notes, and snippets.

@sawaYch
Created October 27, 2018 17:59
Show Gist options
  • Save sawaYch/0eae700b87c51c6a598632a1ce7df7ca to your computer and use it in GitHub Desktop.
Save sawaYch/0eae700b87c51c6a598632a1ce7df7ca to your computer and use it in GitHub Desktop.
Fixer: currency rates api ; demo using C++ with Boost
#include <boost/asio.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/filesystem.hpp>
#include <iostream>
#include "apiKey.h"
using namespace boost::asio::ip;
using namespace boost::asio;
using namespace std;
using namespace boost::filesystem;
namespace pt = boost::property_tree;
int main() {
const string rest_api_server_host = "data.fixer.io";
const string port = "80";
const string data_path = "data/data.json";
path my_path(data_path);
boost::system::error_code ec;
io_service svc;
tcp::resolver resolver(svc);
tcp::resolver::query query(rest_api_server_host, port);
tcp::resolver::iterator iter = resolver.resolve(query);
tcp::endpoint endpoint = iter->endpoint();
tcp::socket sock(svc);
sock.connect(endpoint);
// RESTful GET
string request("GET /api/latest?access_key="+ apiKeyVault::get_apiKey() +"&format=1\r\n\r\n");
sock.send(buffer(request));
// read response
string response;
do {
char buf[1024];
size_t bytes_transferred = sock.receive(buffer(buf), {}, ec);
if (!ec) {
response.append(buf, buf + bytes_transferred);
}
} while (!ec);
// list out what we get
// cout << "Response received: '" << response << "'\n";
cout << "Data received." << endl;
remove_all("data");
create_directory("data");
std::ofstream file( "data/data.json" );
file << response;
file.close();
if ( !exists( "data/data.json" ) )
cout << "new data has been updated.\n";
// Create a root
pt::ptree root;
// Load the json file in this ptree
pt::read_json("data/data.json", root);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment