首页 > 解决方案 > 使用 ESP8266HTTPClient 不断收到 HTTP 400 错误

问题描述

ESP8266HTTPClient我正在尝试使用该库将数据发布到 URL ,但我不断收到 400 个错误。我验证了我可以通过 Postman 发布到该 URL,所以我不确定为什么它在这个草图上一直失败。

输出是:

发送数据到https://my-project.firebaseio.com/users/MY_USER_ID.json {"timestamp":"2021-10-28 14:20:00","duration":"1"}

HTTP 响应代码:400

完整代码如下:

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.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)
    {
      WiFiClient client;
      HTTPClient http;

      String url = baseUrl + "/users/" + userId + ".json";

      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);

      http.end();
    }

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

    shouldSendData = false;
  }
}

标签: firebasearduino-esp8266

解决方案


推荐阅读