欧美一区二区三区,国内熟女精品熟女A片视频小说,日本av网,小鲜肉男男GAY做受XXX网站

c 請求url返回json

洪振霞2年前7瀏覽0評論

C語言可以實現請求一個URL并返回JSON的操作。使用libcurl庫和cJSON庫,可以輕松實現。

#include#include#include#include "cJSON.h"
size_t write_callback(char *ptr, size_t size, size_t nmemb, void* userdata) {
char* response = userdata;
strcat(response, ptr);
return size * nmemb;
}
int main() {
CURL* curl_handle;
CURLcode res;
char* response = malloc(sizeof(char));
response[0] = '\0';
cJSON *root;
cJSON *data;
//初始化curl
curl_global_init(CURL_GLOBAL_ALL);
curl_handle = curl_easy_init();
//設置請求參數
curl_easy_setopt(curl_handle, CURLOPT_URL, "https://api.github.com/users/octocat");
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, write_callback);
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, response);
//發送請求
res = curl_easy_perform(curl_handle);
if(res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
} else {
//解析JSON
root = cJSON_Parse(response);
data = cJSON_GetObjectItem(root, "name");
printf("Name: %s\n", data->valuestring);
}
//清理
curl_easy_cleanup(curl_handle);
free(response);
curl_global_cleanup();
return 0;
}

上面的代碼通過curl庫向https://api.github.com/users/octocat發送了一個請求,并將返回值存儲在一個字符串中。然后使用cJSON庫解析返回的JSON數據,提取名字并打印輸出。