Skip to content

Instantly share code, notes, and snippets.

@michaelgugino
Last active December 13, 2016 22:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaelgugino/915ff6d8519b9e47652d0252890fcd5d to your computer and use it in GitHub Desktop.
Save michaelgugino/915ff6d8519b9e47652d0252890fcd5d to your computer and use it in GitHub Desktop.
/*
Demo json + libcurl cpp program
Copyright (C) 2016 Michael Gugino
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <curl/curl.h>
#include <string>
#include <sstream>
#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
namespace pt = boost::property_tree;
int main(void)
{
CURL *curl;
CURLcode res;
struct curl_slist *list=NULL;
char *bp;
size_t size;
FILE *response_memfile;
pt::ptree root;
curl_global_init(CURL_GLOBAL_DEFAULT);
std::stringstream ss;
curl = curl_easy_init();
if(curl) {
list = curl_slist_append(list, "Accept: application/json");
if (list == NULL) {
curl_easy_cleanup(curl);
curl_global_cleanup();
return 1;
}
response_memfile = open_memstream (&bp, &size);
if (response_memfile == NULL) {
curl_easy_cleanup(curl);
curl_global_cleanup();
return 1;
}
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)response_memfile);
curl_easy_setopt(curl, CURLOPT_URL, "https://www.foaas.com/linus");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list);
#ifdef SKIP_PEER_VERIFICATION
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
#endif
#ifdef SKIP_HOSTNAME_VERIFICATION
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
#endif
res = curl_easy_perform(curl);
/* Check for errors */
if(res != CURLE_OK) {
std::cout << "curl easy perform failed";
}
else {
fflush(response_memfile);
// This feels dirty, but I don't have many options considering
// that curl requires a FILE * object and pt::read_json wants
// a stream and will not accept a FILE *.
ss << bp;
// Load the json file in this ptree
pt::read_json(ss, root);
std::cout << root.get<std::string>("message");
}
/* cleanup */
curl_easy_cleanup(curl);
fclose(response_memfile);
free(bp);
}
curl_global_cleanup();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment