ps:实验环境 arduino ide
apifox测试发送json数据
自己手机提供热点(AP频段最好设置在2.4hz,不然可能会检测不到wifi)
此博客用于记录自己的学习过程,干货较少。
1.esp32创建webserver
下面是所有代码,只需要修改wifi名称和密码就能直接运行。
#include <WiFi.h>
#include <WebServer.h>
#include <ArduinoJson.h>
//自己的WiFissid和password
const char* ssid = "xxx";
const char* password = "xxx";
//创建web服务器
WebServer server(8080);
void setup()
{
Serial.begin(115200);
Serial.println("Start Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected successfully");
Serial.print("Got IP: ");
Serial.println(WiFi.localIP()); //Show ESP32 IP on serial
server.on("/",HTTP_GET,handle_root);//设置程序运行的路由
server.on("/post",HTTP_POST,handlereceive);//设置程序运行的路由
server.begin();
Serial.println("HTTP server started");
delay(100);
}
void loop() {
server.handleClient();//运行服务器
}
//打印纯文本的ESP32-TEST-SERVER
void handle_root()
{
server.send(200, "text/plain", "ESP32-TEST-SERVER");
}
//接受json数据函数并串口打印出来u
void handlereceive()
{
if (server.method() == HTTP_POST)
{
String jsonStr = server.arg("plain");
DynamicJsonDocument jsonDoc(1024);
DeserializationError error = deserializeJson(jsonDoc, jsonStr);
if (error)
{
server.send(400, "text/plain", "Invalid JSON data");
return;
}
int drainTotalCount = jsonDoc["drain_total_count"];
int time = jsonDoc["time"];
Serial.print("drain_total_count: ");
Serial.println(drainTotalCount);
Serial.print("time: ");
Serial.println(time);
server.send(200, "text/plain", "JSON data received and processed");
} else
{
server.send(200, "text/html", "Hello from ESP32 Web Server!");
}
}
1.设置连接信息,连接wifi
2.创建Web服务器
WebServer server(8080);
3.定义处理程序
void handle_root()
{
server.send(200, "text/plain", "ESP32-TEST-SERVER");
}服务器显示纯文本的ESP32-TEST-SERVER
4.设置路由 使用 server.on() 函数来设置路由,将URL路径与相应的处理程序关联起来
server.on("/",HTTP_GET,handle_root);
在根路径下面运行handle_root
5.运行服务器
server.handleClient();
然后我们可以直接登录我们的服务器(要在一个局域网之下)可以直接输入ip,也可以输入
http://ip:端口/,后面接自己设置的路径
2.使用apifox
创建新项目,填入URL http://192.168.1.208:80/post,选择请求body为json,自己定义json数, 这个是我自己创建的路径在这个路径下面接受post来的json数据,点击发送之后,esp32就能直接收到数据了,json数据格式如下。
{
"time":300,
"drain_total_count":500
}
3.另外的讨论
之后我也想过有没有什么办法可以接受到外网的数据,可以使用路由器去进行端口映射,需要将端口映射到一个公共ip上面去,好像比较麻烦。没什么意义,只是自己想想。