ESP32 是一款功能强大的微控制器,支持 Wi-Fi 和蓝牙功能。通过它,我们可以轻松实现与互联网的连接,并访问远程 API 接口。本文将详细讲解如何使用 ESP32 通过 HTTP 协议访问 API 接口,包括所需的基本概念、代码实现以及调试技巧。
HTTP(HyperText Transfer Protocol)是用于在网络上传输数据的应用层协议。它是客户端和服务器之间通信的基础。常见的 HTTP 请求方法有:
API(Application Programming Interface)是一组规则和定义,允许不同软件系统之间进行交互。通过 HTTP 协议,我们可以通过 URL 地址调用远程 API 接口,并传递参数或接收返回的数据。
ESP32 内置了 Wi-Fi 和蓝牙模块,可以方便地连接到互联网。借助 Arduino IDE 或其他开发环境,我们可以使用 WiFiClient
类来发送 HTTP 请求并处理响应。
我们将使用一个公开的测试 API,例如 JSONPlaceholder。这个 API 提供了一些虚拟的资源,适合用来测试 HTTP 请求。
首先需要让 ESP32 连接到 Wi-Fi 网络。以下是一个简单的代码示例:
#include <WiFi.h>
const char* ssid = "YourSSID"; // 替换为你的 Wi-Fi 名称
const char* password = "YourPassword"; // 替换为你的 Wi-Fi 密码
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi!");
}
void loop() {
// 主循环代码
}
接下来,我们编写代码发送一个 HTTP GET 请求到指定的 API 接口。以下是完整代码示例:
#include <WiFi.h>
#include <HTTPClient.h>
const char* ssid = "YourSSID";
const char* password = "YourPassword";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi!");
// 发送 HTTP GET 请求
HTTPClient http;
String url = "https://jsonplaceholder.typicode.com/posts/1"; // 测试 API 地址
http.begin(url); // 指定目标 URL
int httpResponseCode = http.GET(); // 发送 GET 请求
if (httpResponseCode > 0) {
Serial.print("HTTP Response Code: ");
Serial.println(httpResponseCode);
String payload = http.getString(); // 获取响应内容
Serial.println("Response Payload:");
Serial.println(payload);
} else {
Serial.print("Error on sending GET request: ");
Serial.println(httpResponseCode);
}
http.end(); // 关闭 HTTP 连接
}
void loop() {
// 循环部分可以留空
}
如果 API 返回的是 JSON 格式的数据,可以使用 ArduinoJson
库解析。以下是一个解析 JSON 的示例:
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h> // 需要安装 ArduinoJson 库
void setup() {
Serial.begin(115200);
WiFi.begin("YourSSID", "YourPassword");
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi!");
HTTPClient http;
String url = "https://jsonplaceholder.typicode.com/posts/1";
http.begin(url);
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
String payload = http.getString();
Serial.println("Response Payload:");
Serial.println(payload);
DynamicJsonDocument doc(1024); // 创建 JSON 文档
deserializeJson(doc, payload); // 解析 JSON
// 读取 JSON 中的字段
int userId = doc["userId"];
int id = doc["id"];
String title = doc["title"];
String body = doc["body"];
Serial.print("UserId: "); Serial.println(userId);
Serial.print("Id: "); Serial.println(id);
Serial.print("Title: "); Serial.println(title);
Serial.print("Body: "); Serial.println(body);
} else {
Serial.print("Error on sending GET request: ");
Serial.println(httpResponseCode);
}
http.end();
}
void loop() {}
如果需要访问 HTTPS 加密的 API 接口,可以使用 WiFiClientSecure
类替代 WiFiClient
。需要注意的是,ESP32 对证书验证的支持有限,可能需要跳过证书验证。
以下是一个发送 POST 请求的示例代码:
HTTPClient http;
String url = "https://jsonplaceholder.typicode.com/posts";
http.begin(url);
http.addHeader("Content-Type", "application/json");
String postData = "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}";
int httpResponseCode = http.POST(postData);
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println(response);
} else {
Serial.print("Error on sending POST request: ");
Serial.println(httpResponseCode);
}
http.end();