I. Overview
The current article introduces how to use the C language to call the libcurl library to obtain the weather forecast under Linux (Ubuntu). Access Baidu Weather API through HTTP GET request, and parse the returned JSON data, you can get the weather forecast information for the next 7 days for the specified city.
2. Design ideas
[1] Use the libcurl library for HTTP GET requests
- Include the header file in your code
<curl/curl.h>
to use the libcurl library curl_easy_init()
Initialize curl with a function- Set request options, including URL, write callback function and write data parameters
curl_easy_perform()
Execute the request using a function
[2] Write a callback function to store the response data in memory
- Define a structure that contains pointers and lengths for storing response data
- Copy the response data to the memory in the callback function, and dynamically adjust the memory size
- Returns the size of the copied data
[3] Parsing JSON data
- Use
json_tokener_parse()
a function to parse the returned JSON data - Use
json_object_object_get_ex()
a function to get the value of a specified field - Use
json_object_array_length()
a function to get the length of an array - Use
json_object_array_get_idx()
a function to get an element in an array - Use
json_object_get_string()
function to get string value
【4】Print weather forecast information
- Traverse the obtained weather forecast data, and obtain the date, weather and temperature in sequence
- Use
printf()
the function to print the weather forecast information for each day
3. Key code
Here is the main code snippet:
// 定义回调函数,用于将响应数据存储在内存中
size_t write_callback(void *ptr, size_t size, size_t nmemb, void *stream) {
// ...
}
// 子函数,用于获取指定城市未来7天的天气预报
int get_weather_forecast(const char *city) {
// ...
}
int main() {
const char *city = "your_city_code";
int ret = get_weather_forecast(city);
// ...
}
4. Instructions for use
[1] Replace the API key and city code: In the sample code, replace your_ak
and your_city_code
with your own Baidu API key and city code.
[2] Compile the code: Use a suitable C compiler, such as gcc, to compile the code.
gcc -o download_program download_program.c -lcurl
[3] Run the code: run the generated executable file in the terminal.
./download_program
【4】Check the weather forecast: The program will print out the weather forecast information for the next 7 days in the specified city.
Five, complete code
HTTP GET requests access to Baidu Weather API, and parses the returned JSON data to obtain the required weather information.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include <json-c/json.h>
// 定义回调函数,用于将响应数据存储在内存中
size_t write_callback(void *ptr, size_t size, size_t nmemb, void *stream) {
size_t realsize = size * nmemb;
struct string *mem = (struct string *)stream;
mem->ptr = realloc(mem->ptr, mem->len + realsize + 1);
if (mem->ptr == NULL) {
fprintf(stderr, "内存分配失败\n");
return 0;
}
memcpy(&(mem->ptr[mem->len]), ptr, realsize);
mem->len += realsize;
mem->ptr[mem->len] = '\0';
return realsize;
}
// 子函数,用于获取指定城市未来7天的天气预报
int get_weather_forecast(const char *city) {
char url[256];
sprintf(url, "https://api.map.baidu.com/weather/v1/?district_id=%s&ak=your_ak", city);
CURL *curl = curl_easy_init();
struct string response;
response.ptr = malloc(1);
response.len = 0;
if (curl && response.ptr) {
// 设置请求选项
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
// 执行请求
CURLcode res = curl_easy_perform(curl);
if (res != CURLE_OK) {
fprintf(stderr, "请求失败: %s\n", curl_easy_strerror(res));
free(response.ptr);
curl_easy_cleanup(curl);
return -1;
}
// 解析JSON数据
struct json_object *json = json_tokener_parse(response.ptr);
if (json == NULL) {
fprintf(stderr, "JSON解析失败\n");
free(response.ptr);
curl_easy_cleanup(curl);
return -1;
}
// 解析天气预报
struct json_object *result, *weather_data;
json_object_object_get_ex(json, "result", &result);
json_object_object_get_ex(result, "weather_data", &weather_data);
int i;
int num_days = json_object_array_length(weather_data);
for (i = 0; i < num_days; i++) {
struct json_object *day = json_object_array_get_idx(weather_data, i);
const char *date, *weather, *temperature;
date = json_object_get_string(json_object_object_get(day, "date"));
weather = json_object_get_string(json_object_object_get(day, "weather"));
temperature = json_object_get_string(json_object_object_get(day, "temperature"));
printf("日期:%s\n天气:%s\n温度:%s\n\n", date, weather, temperature);
}
free(response.ptr);
json_object_put(json);
} else {
fprintf(stderr, "初始化失败\n");
if (response.ptr) {
free(response.ptr);
}
if (curl) {
curl_easy_cleanup(curl);
}
return -1;
}
curl_easy_cleanup(curl);
return 0;
}
int main() {
const char *city = "your_city_code";
int ret = get_weather_forecast(city);
if (ret == 0) {
printf("天气预报获取成功!\n");
} else {
printf("天气预报获取失败!\n");
}
return 0;
}
In the sample code, use curl_easy_setopt
the function to set the URL of the HTTP GET request, and specify the callback function with the CURLOPT_WRITEFUNCTION
and CURLOPT_WRITEDATA
option to store the response data in memory.
Then, use json_tokener_parse
the function to parse the returned JSON data and extract the weather forecast information. Obtain data in JSON objects and arrays through functions such as json_object_object_get
and .json_object_array_get_idx
YOUR_AK
Note: The and in the URL in the code YOUR_CITY_CODE
need to be replaced with your own Baidu API key and city code.
By calling get_weather_forecast
the function, you can get the weather forecast of the specified city in the next 7 days and print it out.