3 Star 1 Fork 3

marich777/第四组项目代码

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
jrsc.c 3.12 KB
一键复制 编辑 原始数据 按行查看 历史
joysuff 提交于 2024-07-04 14:45 . 调用今日诗词api
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include <cjson/cJSON.h>
// 回调函数,用于处理服务器响应数据
size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t totalSize = size * nmemb;
strncat(userp, contents, totalSize);
return totalSize;
}
// 打印解析的 JSON 数据
void print_parsed_data(const char *response, size_t size) {
// 解析 JSON 响应
cJSON *json = cJSON_ParseWithLength(response, size);
if (json == NULL) {
fprintf(stderr, "解析 JSON 失败: [%s]\n", cJSON_GetErrorPtr());
return;
}
// 获取 "data" 对象
cJSON *data = cJSON_GetObjectItemCaseSensitive(json, "data");
if (!cJSON_IsObject(data)) {
fprintf(stderr, "JSON 格式错误: 找不到 'data' 对象\n");
cJSON_Delete(json);
return;
}
// 获取并打印 "region" 字符串
cJSON *region = cJSON_GetObjectItemCaseSensitive(data, "region");
if (cJSON_IsString(region) && (region->valuestring != NULL)) {
printf("Region: %s\n", region->valuestring);
} else {
fprintf(stderr, "JSON 格式错误: 找不到 'region' 字符串\n");
}
// 获取并打印 "weatherData" 对象
cJSON *weatherData = cJSON_GetObjectItemCaseSensitive(data, "weatherData");
if (cJSON_IsObject(weatherData)) {
cJSON *temperature = cJSON_GetObjectItemCaseSensitive(weatherData, "temperature");
if (cJSON_IsNumber(temperature)) {
printf("Temperature: %d\n", temperature->valueint);
}
cJSON *weather = cJSON_GetObjectItemCaseSensitive(weatherData, "weather");
if (cJSON_IsString(weather) && (weather->valuestring != NULL)) {
printf("Weather: %s\n", weather->valuestring);
}
// 其他天气数据可以按类似方式提取和打印
} else {
fprintf(stderr, "JSON 格式错误: 找不到 'weatherData' 对象\n");
}
// 释放 JSON 对象
cJSON_Delete(json);
}
int main(void) {
CURL *client;
CURLcode err;
char buffer[8192] = {0}; // 用于存储响应数据
// 初始化 CURL
curl_global_init(CURL_GLOBAL_ALL);
client = curl_easy_init();
// 设置 CURL 选项
curl_easy_setopt(client, CURLOPT_URL, "https://v2.jinrishici.com/info");
curl_easy_setopt(client, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(client, CURLOPT_WRITEDATA, buffer);
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "X-User-Token: o9M10gtneoIxRLk5UO13fUG7guYxnS7h"); // 替换 YOUR_API_KEY 为你的 API Key
curl_easy_setopt(client, CURLOPT_HTTPHEADER, headers);
// 执行 CURL 请求
err = curl_easy_perform(client);
if (err != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() 失败: %s\n", curl_easy_strerror(err));
} else {
// // 打印响应数据
// printf("Response data: %s\n", buffer);
// 解析并打印 JSON 数据
print_parsed_data(buffer, strlen(buffer));
}
// 清理资源
curl_slist_free_all(headers);
curl_easy_cleanup(client);
curl_global_cleanup();
return 0;
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/marich777/work.git
git@gitee.com:marich777/work.git
marich777
work
第四组项目代码
master

搜索帮助