ESP32_HTTP请求获取天气,含json解析


//安装 [email protected]
#include "WiFi.h"
#include "HTTPClient.h"
#include "ArduinoJson.h"
 
//**********宏、常量********************
//WIFI名和密码
const char *ssid = "";                         //SSID
const char *password = "";        //PASSWORD
 
//心知天气配置
const char *private_key = "SJo8p9FiiIu6gDNz4";    //私钥
const char *city = "guangzhou";                   //查询的城市
const char *day = "3";                            //查询几日内的天气(免费用户最多可查3日)
 
//**********全局变量********************
String http_req;           //http请求
String http_rsp;           //http应答
HTTPClient http_client;
DynamicJsonDocument doc(2048);  //json
 
//***********函数声明*******************
void WIFI_Config(void);           //连接WIFI
void set_weather_httpclient(void);//设置获取天气的接口
void anylasize_weather_json(String jsonStr);
 
//***********初始化*********************
void setup()
{
  Serial.begin(115200);
  WIFI_Config();                
  set_weather_httpclient();
}
 
//***********循环************************
void loop()
{
  int http_code = http_client.GET();
  
  if (http_code == HTTP_CODE_OK) {
    http_rsp = http_client.getString();
    Serial.println(http_rsp);             //打印原始的http响应
    anylasize_weather_json(http_rsp);
    while(1);
  }else{
    Serial.printf("HTTP get code: %d\n", http_code);
  }
  delay(5000);
}
 
//***********函数实现*******************
//连接WIFI
void WIFI_Config()
{
  Serial.println("connecting WIFI");
  WiFi.begin(ssid, password);
  while (!WiFi.isConnected()){        //等待连接
    Serial.print(".");
    delay(500);
  }
  Serial.println("Wifi connected\n");   //连接成功
}
 
//设置获取天气的接口
void set_weather_httpclient()
{
  http_req = (String)"https://api.seniverse.com/v3/weather/daily.json?key=" + private_key ;
  http_req += (String)"&location=" + city + "&language=en&unit=c&start=0&days=" + day;
  Serial.println(http_req);
  if (http_client.begin(http_req)){
    Serial.println("set_weather_httpclient ok.\n");
  }
}
 
//解析JSON字符串
//{"results":[{"location":{"id":"WS0E9D8WN298","name":"Guangzhou","country":"CN","path":"Guangzhou,Guangzhou,Guangdong,China","timezone":"Asia/Shanghai","timezone_offset":"+08:00"},"daily":[{"date":"2023-10-07","text_day":"Overcast","code_day":"9","text_night":"Overcast","code_night":"9","high":"26","low":"20","rainfall":"0.00","precip":"0.00","wind_direction":"N","wind_direction_degree":"2","wind_speed":"21.06","wind_scale":"4","humidity":"73"},{"date":"2023-10-08","text_day":"Overcast","code_day":"9","text_night":"Overcast","code_night":"9","high":"25","low":"21","rainfall":"0.00","precip":"0.00","wind_direction":"NE","wind_direction_degree":"63","wind_speed":"23.94","wind_scale":"4","humidity":"71"},{"date":"2023-10-09","text_day":"Overcast","code_day":"9","text_night":"Overcast","code_night":"9","high":"26","low":"23","rainfall":"0.00","precip":"0.00","wind_direction":"NE","wind_direction_degree":"30","wind_speed":"13.46","wind_scale":"3","humidity":"71"}],"last_update":"2023-10-07T20:00:00+08:00"}]}
void anylasize_weather_json(String jsonStr)
{ 
  int index = jsonStr.indexOf('{');         //找到json的{
  jsonStr = jsonStr.substring(index);
    
  deserializeJson(doc, jsonStr);            //字符串解析成json格式 
  JsonObject root = doc.as();   //doc转换成的JsonObject对象root  
  
  JsonArray results = root["results"];      //JsonObject对象root里有JsonArray数组results
  
  JsonObject location = results[0]["location"]; //results[0]中的子JsonObject对象location  
  const char *name = location["name"];          //JsonObject对象location中取出name(城市名)  Guangzhou
  Serial.println(name);
 
  JsonArray daily = results[0]["daily"];        //results[0]中的JsonArray数组daily
  const char *date = daily[0]["date"];          //JsonArray数组daily中[0]的“date”(日期)  2023-10-07
  Serial.println(date);
  const char *weather = daily[0]["text_day"];   //JsonArray数组daily中[0]的“text_day”(天气)  Overcast
  Serial.println(weather);
  const char *low = daily[0]["low"];            //JsonArray数组daily中[0]的最低和最高气温  temper is 20~26 deg
  const char *high = daily[0]["high"];
  Serial.println((String)"temper is "+low+"~"+high+" deg");  
}
 

参考:ESP32_HTTP请求获取天气,含json解析_esp32 心知天气_PWRJOY的博客-CSDN博客

你可能感兴趣的:(ESP32,http,json,ESP32,网络)