1. 简介
- 官方文档
https://docs.espressif.com/projects/esp-idf/zh_CN/latest/esp32/api-reference/protocols/esp_http_server.html
- 官方例程
https://gitee.com/EspressifSystems/esp-idf/tree/master/examples/protocols/http_server/simple
Simple HTTPD Server Example
该示例包括HTTPD服务器演示和URI处理的演示:
1) URI\hello for GET命令返回“hello World!”信息
2) POST命令的URI\echo回显POST发布的消息
2. 开发环境
《Win10启用Linux子系统安装Ubuntu》
https://blog.csdn.net/chentuo2000/article/details/112131624
《用乐鑫国内Gitee镜像搭建ESP32开发环境》
https://blog.csdn.net/chentuo2000/article/details/113424934
3. 构建项目
- 复制官方例程
将官方例子项目复制到ESP-IDF开发工具之外,更名为esp32_gatt_client:
cp -r ~/esp/esp-idf/examples/protocols/http_server/simple ~/esp/http_server_simple
- 项目树
cd ~/esp/http_server_simple
- 刷新esp-idf环境
get_idf
- 配置项目
idf.py menuconfig
保存,退出。
- 编译项目
idf.py build
- 烧写项目
连接设备时我PC将USB-SERIAL识别为COM3。
idf.py -p /dev/ttyS3 -b 115200 flash
4. 测试
4.1 上电启动
- 查看串口输出
4.2 命令行测试cURL
cURL是一个利用URL语法在命令行下工作的文件传输工具。
1) GET测试
curl 192.168.0.102:80/hello
测试GET "\hello"处理。
串口显示:
2) POST测试
curl -X POST --data-binary @mqtt_cinfig.txt 192.168.0.102:80/echo > tmpfile
发送当前目录下测文件mqtt_cinfig.txt,文件内容:
username: ct
password: 12345678
串口显示:
发送的文件被服务器的echo命令返回,在当前目录保存为tmpfile。两个文件是一样的。
3) 禁用/hello和/echo处理
curl -X PUT -d "0" 192.168.0.102:80/ctrl
这时再执行curl 192.168.0.102:80/hello命令:
返回404错误。
同样再执行
curl -X POST --data-binary @mqtt_cinfig.txt 192.168.0.102:80/echo > tmpfile
命令:
也返回404错误。
4) 启用/hello和/echo处理
curl -X PUT -d "1" 192.168.0.102:80/ctrl
4.3 浏览器测试
在浏览器输入http://192.168.0.102
串口显示:
浏览器显示
修改配置:
idf.py menuconfig
Component config -> HTTP Server -> Max HTTP Request Header Length
将512改成1024。
编译烧写,再测试:
在浏览器输入http://192.168.0.102
串口显示:
浏览器显示
5. 读取URL请求串和参数
- 请求hello,带3个参数
http://192.168.0.102:80/hello?query1=abc&query2=ABD&query3=123
- 浏览器输入
- 串口响应
- 处理代码