C 獲取鏈接返回 JSON CNDs
#include <stdio.h> #include <curl/curl.h> #include <jansson.h> int main(void) { CURL *curl; CURLcode res; char *url = "http://example.com/api/cdns"; char *data; size_t len; curl = curl_easy_init(); if(curl) { curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &data); res = curl_easy_perform(curl); if(res != CURLE_OK) { fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); } curl_easy_cleanup(curl); } json_t *root; json_error_t error; root = json_loads(data, 0, &error); if (!root) { fprintf(stderr, "json_loads error: %s\n", error.text); return 1; } json_t *cdns_object = json_object_get(root, "cdns"); if (!json_is_array(cdns_object)) { fprintf(stderr, "json is not an array\n"); json_decref(root); return 1; } size_t index; json_t *value; json_array_foreach(cdns_object, index, value) { if (!json_is_string(value)) { fprintf(stderr, "json is not a string\n"); json_decref(root); return 1; } printf("%s\n", json_string_value(value)); } json_decref(root); return 0; } size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userdata) { size_t realsize = size * nmemb; char *data = (char*)userdata; data = realloc(data, realsize + 1); if (data) { memcpy((data + strlen(data)), ptr, realsize); *(data + strlen(data) + realsize) = 0; } return realsize; }