基于accuweather Linux C实例
时间: 2024-04-27 20:23:38 浏览: 200
以下是一个基于 AccuWeather API 的 Linux C 示例代码,它可以获取城市的当前天气信息:
```c
#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>
#include <json-c/json.h>
#define API_KEY "your_api_key"
#define CITY_ID "your_city_id"
struct MemoryStruct {
char *memory;
size_t size;
};
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
struct MemoryStruct *mem = (struct MemoryStruct *)userp;
mem->memory = realloc(mem->memory, mem->size + realsize + 1);
if (mem->memory == NULL) {
printf("Not enough memory (realloc returned NULL)\n");
return 0;
}
memcpy(&(mem->memory[mem->size]), contents, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}
int main(void) {
CURL *curl_handle;
CURLcode res;
struct MemoryStruct chunk;
chunk.memory = malloc(1);
chunk.size = 0;
curl_global_init(CURL_GLOBAL_ALL);
curl_handle = curl_easy_init();
if (curl_handle) {
char url[100];
sprintf(url, "http://dataservice.accuweather.com/currentconditions/v1/%s?apikey=%s", CITY_ID, API_KEY);
curl_easy_setopt(curl_handle, CURLOPT_URL, url);
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk);
res = curl_easy_perform(curl_handle);
if (res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
} else {
struct json_object *parsed_json;
struct json_object *weather;
struct json_object *temperature;
parsed_json = json_tokener_parse(chunk.memory);
json_object_object_get_ex(parsed_json, "WeatherText", &weather);
json_object_object_get_ex(parsed_json, "Temperature", &temperature);
printf("Weather: %s\n", json_object_get_string(weather));
printf("Temperature: %s\n", json_object_get_string(temperature));
json_object_put(parsed_json);
}
curl_easy_cleanup(curl_handle);
}
curl_global_cleanup();
free(chunk.memory);
return 0;
}
```
在此示例中,我们使用了 curl 库来发出 HTTP GET 请求,并使用 json-c 库解析 JSON 响应。你需要将 `API_KEY` 和 `CITY_ID` 更改为你的 AccuWeather API 密钥和所需城市的 ID。
阅读全文