The code below compiles and prints the response.
My question is: being the response a string which represents an object, how can I cast "res" into a string or directly into a JSON object?
#include <stdio.h>
#include <curl/curl.h>
#include <json-c/json.h>
int main(int argc, char **argv) {
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET");
curl_easy_setopt(curl, CURLOPT_URL, "http://localhost:8080/system/genpass");
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "length: 20");
headers = curl_slist_append(headers, "numbers: true");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
res = curl_easy_perform(curl);
printf("%u",res);
}
curl_easy_cleanup(curl);
}
You cannot simply cast the return code of a function into a string. They are not related in any way.
Instead you need to handle the received data directly. For this purpose you need to register a callback function that can handle the data. This is descriped in cURL manual.
Example:
Output:
After the GET request is completed, you can access the data in
req->buffer
and parse for JSON objects or any other data. Error checking (forrealloc
etc.) needs to be added.I used an approach that is able to handle any length of content in any number of chunks received. If you know the length of your expected content, you might go for it with a fixed size buffer.
As you can see in my example, the user data structure still exists after the download is complete and the content can be derived after
curl_easy_perform
returns.