Skip to content

Instantly share code, notes, and snippets.

@jbenner-radham
Created April 9, 2014 14:26
Show Gist options
  • Save jbenner-radham/10276598 to your computer and use it in GitHub Desktop.
Save jbenner-radham/10276598 to your computer and use it in GitHub Desktop.
Curling some JSON for fun!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define CURL_STATICLIB
#include <curl/curl.h>
#include "picojson.h"
using namespace std;
/**
* @link https://github.com/kazuho/picojson
* @link https://stackoverflow.com/questions/2329571/c-libcurl-get-output-into-a-string#answer-2329792
* @link http://xdev.me/en/article/C++_download_a_URL_with_libcurl
*
* Compiling with `-static` makes libcurl blow up, we use `#define CURL_STATICLIB` in the page (or it can be set via compiler flag.)
* `g++ -std=c++11 -Wall curl_test.cpp -lcurl -lwsock32 -lidn -lwldap32 -lssh2 -lrtmp -lcrypto -lz -lws2_32 -lwinmm -lssl`
*/
typedef struct {
char *ptr;
size_t len;
} string_t;
void init_string(string_t *s) {
s->len = 0;
s->ptr = (char*)malloc(s->len + 1);
if (s->ptr == NULL) {
fprintf(stderr, "malloc() failed\n");
exit(EXIT_FAILURE);
}
s->ptr[0] = '\0';
}
size_t write_fn(void *ptr, size_t size, size_t nmemb, string_t *s) {
size_t new_len = s->len + (size * nmemb);
s->ptr = (char*)realloc(s->ptr, new_len + 1);
if (s->ptr == NULL) {
fprintf(stderr, "realloc() failed\n");
exit(EXIT_FAILURE);
}
memcpy(s->ptr+s->len, ptr, size * nmemb);
s->ptr[new_len] = '\0';
s->len = new_len;
return size * nmemb;
}
int main(void)
{
CURL *curl;
CURLcode res;
string_t s;
init_string(&s);
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://localhost/json-test.php");
// Tell libcurl to follow redirection
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_fn);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s);
// Perform the request, res will get the return code
res = curl_easy_perform(curl);
// Check for errors
if (res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
}
const char *json = (const char*)s.ptr;
picojson::value v;
string err = picojson::get_last_error();
picojson::parse(v, json, json + strlen(json), &err);
if (!err.empty()) {
cerr << err << endl;
}
// check if the type of the value is "object"
if (! v.is<picojson::object>()) {
cerr << "JSON is not an object" << endl;
exit(2);
}
// obtain a const reference to the map, and print the contents
const picojson::value::object& obj = v.get<picojson::object>();
for (picojson::value::object::const_iterator i = obj.begin(); i != obj.end(); ++i) {
cout << i->first << ": " << i->second.to_str() << endl;
}
// Always cleanup
curl_easy_cleanup(curl);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment