本文访问的是聚合数据的API获取JSON信息并解析并打印才串口上。
一、创建API
这是聚合数据网址:聚合数据 - API接口开放平台_API接口大全_免费API数据接口服务 (juhe.cn)https://www.juhe.cn/
进入创建号账号后,直接点击顶栏的API选项,之后搜索天气找到
进入后点立即申请创建好自己的API。
在自己的API中找到它,进入后点击接口文档
可以看到这里采用的请求方式是http get或post,返回数据类型是json
这里我们需要用到的是接口地址url,以及需要city和key这两个参数,除此之外你还需要在左栏数据中心里面找到我的API,复制自己请求所需的Key
二、代码部分
首先要引入所需要的库,然后定义所用到的参数:
#include <M5Core2.h>//自己的设备系列
#include <WiFi.h>//WiFi
#include <HTTPClient.h>//
#include <ArduinoJson.h>
const char *ssid = "Room205";//自己的wifi名
const char *password = "hlj125205";//wifi密码
String url = "http://apis.juhe.cn/simpleWeather/query";//定义请求所需的三个参数
String city = "哈尔滨";
String key = "847ae73ffa63a155777e44ddbd340f14";
要获取API首先需要给设备连上网,在void setup中加入这一段连接wifi:
M5.begin();//初始化
Serial.begin(115200);//自己设备的适宜波特率
//连接wifi
WiFi.begin(ssid, password);
Serial.print("正在连接 WiFi");
//检测是否成功
while (WiFi.status() != WL_CONNECTED){
delay(500);
Serial.print(".");
}
Serial.print("连接成功");
接下来就是发送请求接收响应,由请求文档我们可知所需参数:
HTTPClient http; // 创建 HTTPClient 对象
http.begin(url+"?city="+city+"&key="+key);//访问URL,第二个city是变量
int http_code = http.GET();// 接收 HTTP 响应状态码
// Serial.printf("HTTP 状态码:%d", http_code);//因为是int类型所以用%d,如果是字符串则用%s
//获取数据
String response = http.getString();
Serial.print("响应数据");
Serial.print(response);
http.end();
//创建DynamicJsonDocument 对象
DynamicJsonDocument doc(1024);//指定大小
deserializeJson(doc, response);//解析Json数据
String info = doc["result"]["realtime"]["info"].as<String>();//这里就随便抓一个数据读取了
Serial.printf("\n 天气:%s", info);
最后结果像这样: