You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用ESP8266HTTPClient库发起POST请求持续返回HTTP 400错误如何解决

问题原因及解决方案

你的问题核心出在HTTPS请求的客户端类型不匹配,你当前用的是仅支持HTTP协议的WiFiClient类访问Firebase的HTTPS接口,导致请求格式不符合服务器要求,返回400错误。

具体修改步骤

  1. 新增WiFiClientSecure头文件引用
#include <WiFiClientSecure.h>
  1. 将原代码中WiFiClient client;替换为WiFiClientSecure client;,并在发起请求前添加跳过证书校验的配置(测试用,生产环境建议配置对应根证书提高安全性):
WiFiClientSecure client;
HTTPClient http;
// 新增以下行跳过SSL证书校验
client.setInsecure();

String url = baseUrl + "/users/" + userId + ".json";
http.begin(client, url);
  1. 可选:收到响应后打印完整响应内容,方便进一步定位问题:
int httpResponseCode = http.POST(data);
// 新增打印响应体
Serial.print("响应内容:");
Serial.println(http.getString());

如果修改后返回401权限错误,说明你Postman请求时携带了认证参数,代码中未携带,可在URL末尾拼接Firebase认证参数即可,格式为url += "?auth=你的数据库密钥"。

修改后的完整可运行代码

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClientSecure.h>

// WiFi configuration
const char *ssid = "MY_SSID";
const char *password = "MY_PASSWORD";

// Database configuration
const String userId = "MY_USER_ID";
const String baseUrl = "https://my-project.firebaseio.com";

void setup()
{
  delay(1000);
  Serial.begin(9600);

  Serial.print("Configuring access point...");

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(500);
  }

  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
}

bool shouldSendData = true;

void loop()
{
  if (shouldSendData)
  {
    Serial.println("Attempting to send data...");

    if (WiFi.status() == WL_CONNECTED)
    {
      WiFiClientSecure client;
      HTTPClient http;
      // 跳过SSL证书校验,测试用
      client.setInsecure();

      String url = baseUrl + "/users/" + userId + ".json";
      // 如有需要可在此处拼接认证参数:url += "?auth=你的数据库密钥";

      http.begin(client, url);
      http.addHeader("Content-Type", "application/json");

      String data = "{\"timestamp\":\"2021-10-28 14:20:00\",\"duration\":\"1\"}";
      int httpResponseCode = http.POST(data);

      Serial.print("Sending data to ");
      Serial.println(url);
      Serial.println(data);
      Serial.print("HTTP Response code: ");
      Serial.println(httpResponseCode);
      // 打印响应内容方便排查
      Serial.print("Response content: ");
      Serial.println(http.getString());

      http.end();
    }

    else
    {
      Serial.println("Unable to send data. WiFi is not connected.");
    }

    shouldSendData = false;
  }
}

内容的提问来源于stack exchange,提问作者jacobsowles

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 04:36:04