ESP32 HTTP请求实操:GET与POST一次讲清

2026-11-25 20:31:09 11阅读 所属项目:ESP32 开发板

传感器数据要出门,第一站几乎都是 HTTP:往自家服务器报读数、从接口拿配置、调第三方 API 查天气,全靠 GET 和 POST 两种请求打天下。这篇把 ESP32 上最常见的几种写法一次走完:GET 带查询参数、GET 取 JSON、POST 表单编码、POST 发 JSON,示例服务端用树莓派上的 Node-RED 搭,任何能收 HTTP 的服务都通用。

ESP32发起HTTP GET与POST请求的实验主图

先分清 GET 和 POST 的分水岭

GET 用来向指定资源要数据,参数直接拼在 URL 里,比如 update-sensor?temperature=value1,人人可见,适合读接口、查状态。POST 用来提交数据,内容放在请求体里,URL 上看不见——但要记住 HTTP 不加密时请求体照样是明文,敏感信息要走 HTTPS。两种请求都在示例里对应了真实场景:GET 查传感器值,POST 更新传感器读数。

准备:装 Arduino_JSON 库

GET 到的 JSON 要解析,官方教程用的是 Arduino_JSON 库,库管理器里搜名字直接装。服务端方面,树莓派跑 Node-RED 后导入源文给的 flow,就有 /update-sensor 和 /get-sensor 两个现成接口;没有树莓派的话,把代码里的服务器地址换成任何能响应的 API 一样能跑。

Node-RED仪表盘显示ESP32上报的传感器实时数据

GET 带参数上报:URL 里拼读数

第一段示例每 5 秒把一个温度值拼进 URL 发 GET。代码来自源文原样搬运(头文件按平台兼容写法用引号包含):

/*
  Rui Santos
  Complete project details at Complete project details at https://RandomNerdTutorials.com/esp32-http-get-post-arduino/

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*/

#include "WiFi.h"
#include "HTTPClient.h"

const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

//Your Domain name with URL path or IP address with path
String serverName = "http://192.168.1.106:1880/update-sensor";

// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastTime = 0;
// Timer set to 10 minutes (600000)
//unsigned long timerDelay = 600000;
// Set timer to 5 seconds (5000)
unsigned long timerDelay = 5000;

void setup() {
  Serial.begin(115200); 

  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
 
  Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.");
}

void loop() {
  //Send an HTTP POST request every 10 minutes
  if ((millis() - lastTime) > timerDelay) {
    //Check WiFi connection status
    if(WiFi.status()== WL_CONNECTED){
      HTTPClient http;

      String serverPath = serverName + "?temperature=24.37";
      
      // Your Domain name with URL path or IP address with path
      http.begin(serverPath.c_str());
      
      // If you need Node-RED/server authentication, insert user and password below
      //http.setAuthorization("REPLACE_WITH_SERVER_USERNAME", "REPLACE_WITH_SERVER_PASSWORD");
      
      // Send HTTP GET request
      int httpResponseCode = http.GET();
      
      if (httpResponseCode>0) {
        Serial.print("HTTP Response code: ");
        Serial.println(httpResponseCode);
        String payload = http.getString();
        Serial.println(payload);
      }
      else {
        Serial.print("Error code: ");
        Serial.println(httpResponseCode);
      }
      // Free resources
      http.end();
    }
    else {
      Serial.println("WiFi Disconnected");
    }
    lastTime = millis();
  }
}

要点有三处:用 millis() 差值做定时而不是 delay,主循环不被阻塞;发请求前先检查 WiFi.status(),断网时避免无谓超时;http.end() 释放资源,长跑的程序漏了这句会慢慢耗尽连接。串口会打印 HTTP 响应码和返回体,200 才算成功。

GET 取 JSON:解析回结构化数据

反向场景是 ESP32 主动查数据。把地址换成 get-sensor 接口,拿到形如 {"value1":24.25,"value2":49.54,"value3":1005.14} 的 JSON,用 JSON.parse 解析后按键名取值打印。解析前记得用 JSON.typeof 判断类型,接口返回错误页时直接取键会得到 unexpected,这正是很多"偶尔乱码"问题的根因。

GET请求返回JSON数据并解析打印

POST 提交数据:表单编码与 JSON 两种姿势

POST 示例一次给了三种 Content-Type 的写法:x-www-form-urlencoded 用键值对字符串、application/json 发 JSON 对象、text/plain 发纯文本,代码原样贴出:

/*
  Rui Santos
  Complete project details at Complete project details at https://RandomNerdTutorials.com/esp32-http-get-post-arduino/

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*/

#include "WiFi.h"
#include "HTTPClient.h"

const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

//Your Domain name with URL path or IP address with path
const char* serverName = "http://192.168.1.106:1880/update-sensor";

// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastTime = 0;
// Timer set to 10 minutes (600000)
//unsigned long timerDelay = 600000;
// Set timer to 5 seconds (5000)
unsigned long timerDelay = 5000;

void setup() {
  Serial.begin(115200);

  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
 
  Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.");
}

void loop() {
  //Send an HTTP POST request every 10 minutes
  if ((millis() - lastTime) > timerDelay) {
    //Check WiFi connection status
    if(WiFi.status()== WL_CONNECTED){
      WiFiClient client;
      HTTPClient http;
    
      // Your Domain name with URL path or IP address with path
      http.begin(client, serverName);
      
      // If you need Node-RED/server authentication, insert user and password below
      //http.setAuthorization("REPLACE_WITH_SERVER_USERNAME", "REPLACE_WITH_SERVER_PASSWORD");
      
      // Specify content-type header
      http.addHeader("Content-Type", "application/x-www-form-urlencoded");
      // Data to send with HTTP POST
      String httpRequestData = "api_key=tPmAT5Ab3j7F9&sensor=BME280&value1=24.25&value2=49.54&value3=1005.14";           
      // Send HTTP POST request
      int httpResponseCode = http.POST(httpRequestData);
      
      // If you need an HTTP request with a content type: application/json, use the following:
      //http.addHeader("Content-Type", "application/json");
      //int httpResponseCode = http.POST("{\"api_key\":\"tPmAT5Ab3j7F9\",\"sensor\":\"BME280\",\"value1\":\"24.25\",\"value2\":\"49.54\",\"value3\":\"1005.14\"}");

      // If you need an HTTP request with a content type: text/plain
      //http.addHeader("Content-Type", "text/plain");
      //int httpResponseCode = http.POST("Hello, World!");
     
      Serial.print("HTTP Response code: ");
      Serial.println(httpResponseCode);
        
      // Free resources
      http.end();
    }
    else {
      Serial.println("WiFi Disconnected");
    }
    lastTime = millis();
  }
}

和 GET 版的区别在两处:http.begin 要传入 WiFiClient 对象,再由 addHeader 声明内容类型,POST 的数据整体作为 http.POST 的参数。想换 JSON,把 addHeader 的类型改成 application/json,再传序列化好的 JSON 字符串即可,源文里注释掉的几行就是现成写法。

POST请求服务端收到表单与JSON两种数据

调试建议

报错码负数基本是连接层问题:-1 连接失败、-5 连不上服务器,先 ping 服务器 IP 再查端口。响应码 200 之外的常见值:404 是路径写错,401 缺认证,这时打开代码里注释掉的 setAuthorization 两行补上用户名密码。接口调通后,把 timerDelay 从 5 秒改成 10 分钟级别,正式上报别把小服务器打爆。


作者:电机传感器师
链接:https://www.aiddithome.com/p/1b52f18820c1f2.html
本作版权归作者所有,未经允许请勿转载。若存在违规行为,您可以点击 “举报”。


登录 后发表评论
4条评论
板砖搬不动
1楼 · 1小时前

Node-RED那个flow直接导入就能用,省了不少搭服务的时间

拆开看看再说
2楼 · 1小时前

负数错误码排查那段总结得好,-1基本都是连不上

周五下班搞一搞
3楼 · 1小时前

提醒HTTP明文这条很实在,局域网里也别传密码

触底反弹的Tony
4楼 · 1小时前

http.end()那句真是救命的,之前长跑两天内存耗尽就是这个没写