设备:esp32c3
IDE:Arduino
实验:
(1)获取网络时间,b站粉丝数和b站关注数,心知天气
#include "HTTPClient.h"
#include "WiFi.h"
#include "ArduinoJson.h"
char *ssid ="Redmi K40 Gaming";
char *pswd ="87654321";/**获取b站粉丝数和关注up主数量*https://api.bilibili.com/x/relation/stat?vmid=1387378819*vmid为自己b站的uid*返回{"code": 0,"message": "0","ttl": 1,"data": {"mid": 1387378819,"following": 139,"whisper": 0,"black": 1,"follower": 44}
}*/
void GetFollower_Following(void){HTTPClient http;http.begin("https://api.bilibili.com/x/relation/stat?vmid=1387378819");int httpCode=http.GET();DynamicJsonDocument doc(1024);if(httpCode==200) //服务器响应成功{String payload=http.getString();deserializeJson(doc,payload);int follower=doc["data"]["follower"].as<int>();int following=doc["data"]["following"].as<int>();String uid=doc["data"]["mid"].as<String>();Serial.println("用户: "+uid);Serial.printf("粉丝数: %d\r\n",follower); Serial.printf("关注up主数: %d\r\n",following);}http.end();}void ConnectWifi(void)
{WiFi.mode(WIFI_MODE_STA);WiFi.begin(ssid,pswd);Serial.print("连接wifi中");while(WiFi.status()!= WL_CONNECTED){delay(500);Serial.print(".");}Serial.print("连接成功");
}/**连接网络*HTTP 状态码的英文为 HTTP Status Code*200 - 请求成功*301 - 资源(网页等)被永久转移到其它URL*404 - 请求的资源(网页等)不存在*500 - 内部服务器错误*访问http://quan.suning.com/getSysTime.do*返回:{"sysTime2":"2024-04-09 13:56:34","sysTime1":"20240409135634"}*/
void GetTime(void)
{HTTPClient http;http.begin("http://quan.suning.com/getSysTime.do");int httpCode=http.GET();DynamicJsonDocument doc(1024);if(httpCode==200) //服务器响应成功{String payload=http.getString();deserializeJson(doc,payload);String time=doc["sysTime2"].as<String>();Serial.println("当前时间:"); //带ln后缀的,打印后换行Serial.println(time);}http.end();
}/**获取心知天气数据*访问:https://api.seniverse.com/v3/weather/now.json?key=自己的密钥&location=chongqing&language=zh-Hans&unit=c*返回:
{"results": [{"location": {"id": "WM7B0X53DZW2","name": "重庆","country": "CN","path": "重庆,重庆,中国","timezone": "Asia/Shanghai","timezone_offset": "+08:00"},"now": {"text": "阴","code": "9","temperature": "21"},"last_update": "2024-04-09T14:26:30+08:00"}]
}*/
void Get_Weather(String city,String key)
{HTTPClient http;http.begin("https://api.seniverse.com/v3/weather/now.json?key="+key+"&location="+city+"&language=zh-Hans&unit=c");int httpCode=http.GET();DynamicJsonDocument doc(1024);if(httpCode==200) //服务器响应成功{String payload=http.getString();deserializeJson(doc,payload);//results里面中是一个[]代表是数组,而且只有一个数组,即下标为0处中有location,now,last_update三个对象String city=doc["results"][0]["location"]["name"].as<String>();int temperature=doc["results"][0]["now"]["temperature"].as<int>();String weather=doc["results"][0]["now"]["text"].as<String>();Serial.println("所处城市: "+city); //带ln后缀的,打印后换行Serial.println("天气状况: "+weather);Serial.printf("气温: %d ℃",temperature);}http.end();
}
void setup() {// put your setup code here, to run once:
Serial.begin(115200);
ConnectWifi();
GetTime();
GetFollower_Following();
Get_Weather("chongqing","私钥");
}void loop() {// put your main code here, to run repeatedly:}