HTTP 客户端获取天气 API
2026-05-07 Thursday
ESP32 HTTP GET/POST请求 · JSON解析ArduinoJson库 · 和风天气API实战
概述
连上 WiFi 之后干什么?当然是上网拿数据!本篇教你用 ESP32 作为 HTTP 客户端,请求互联网 API,获取实时天气数据并解析 JSON。
学习目标
- 掌握 HTTP GET/POST 请求
- 理解 JSON 解析
- 学会使用 ArduinoJson 库
物料清单
| 元件 | 数量 |
|---|---|
| ESP32 开发板 | x1 |
| WiFi 网络 | — |
| 和风天气 API Key | 免费注册 |
实战:获取天气
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) delay(500);
HTTPClient http;
http.begin("https://devapi.qweather.com/v7/weather/now?location=101010100&key=YOUR_KEY");
int code = http.GET();
if (code == 200) {
DynamicJsonDocument doc(1024);
deserializeJson(doc, http.getString());
Serial.println(doc["now"]["temp"].as<String>() + "°C");
}
http.end();
}
注册和风天气免费开发者账号即可获取 API Key。