从ESP8266 Arduino板向服务器发布JSON对象的问题

发布于 2025-02-03 07:10:47 字数 2228 浏览 6 评论 0原文

我正在尝试将JSON对象发布到ESP8266板上部署在Heroku上的服务器。

我的问题是我没有发布任何内容,或者我发布了错误的JSON对象,因为Heroku Logs显示了500个错误,并且我在串行显示器上获得了一个空对象。

我的理解是我正确击中服务器,但是JSON对象的格式是错误的,或者我缺少帖子方法中的某些内容。

您能检查我的代码并帮助我找到解决方案吗?

这是我的代码:

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

const char *host = "appname.herokuapp.com";
const char* serverName = "https://appname.herokuapp.com";
const char* ssid = "*******"; 
const char* password = "*******";

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

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

void loop() {

  if(WiFi.status()== WL_CONNECTED) {
      std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
      client->setInsecure();
     
      HTTPClient https;

      DynamicJsonDocument doc(512);
      JsonObject object = doc.to<JsonObject>();
      object["temperature"] = 30;
      String data;
      serializeJsonPretty(object, data);

      Serial.println(data);

      https.addHeader("Accept:", "application/json");
      https.addHeader("Host:", host);

      if (https.begin(*client, serverName)) {
          Serial.print("[HTTPS] POST...\n");
          int httpCode = https.POST(data);

          if (httpCode > 0) {
            Serial.printf("[HTTPS] POST... code: %d\n", httpCode);
            
            if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
              String payload = https.getString();
              Serial.println(payload);

            } else {
              Serial.printf("[HTTPS] POST... failed, error: %s\n", https.errorToString(httpCode).c_str());
            }

          } else  {
            Serial.printf("[HTTPS] POST... failed, error: %s\n", https.errorToString(httpCode).c_str());
          }
          https.end();

    } else {
      Serial.printf("[HTTPS] Unable to connect\n");
    } 
  }
  delay(5000);
}

I am trying to post a JSON object to a server deployed on Heroku from an ESP8266 board.

My problem is that I am not posting anything or I am posting a wrong JSON object, as Heroku logs show a 500 error and I am getting an empty object on the serial monitor.

My understanding is that I am hitting the server correctly, but either the format of the JSON object is wrong or I am missing something in my post method.

Could you please check my code and help me find a solution?

Here is my code:

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

const char *host = "appname.herokuapp.com";
const char* serverName = "https://appname.herokuapp.com";
const char* ssid = "*******"; 
const char* password = "*******";

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

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

void loop() {

  if(WiFi.status()== WL_CONNECTED) {
      std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
      client->setInsecure();
     
      HTTPClient https;

      DynamicJsonDocument doc(512);
      JsonObject object = doc.to<JsonObject>();
      object["temperature"] = 30;
      String data;
      serializeJsonPretty(object, data);

      Serial.println(data);

      https.addHeader("Accept:", "application/json");
      https.addHeader("Host:", host);

      if (https.begin(*client, serverName)) {
          Serial.print("[HTTPS] POST...\n");
          int httpCode = https.POST(data);

          if (httpCode > 0) {
            Serial.printf("[HTTPS] POST... code: %d\n", httpCode);
            
            if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
              String payload = https.getString();
              Serial.println(payload);

            } else {
              Serial.printf("[HTTPS] POST... failed, error: %s\n", https.errorToString(httpCode).c_str());
            }

          } else  {
            Serial.printf("[HTTPS] POST... failed, error: %s\n", https.errorToString(httpCode).c_str());
          }
          https.end();

    } else {
      Serial.printf("[HTTPS] Unable to connect\n");
    } 
  }
  delay(5000);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鲸落 2025-02-10 07:10:47

问题是要将邮政方法嵌套在IF语句中,而不是在添加标题后将其嵌套。
我已经修改了代码,现在可以使用。

void loop() {

  if(WiFi.status()== WL_CONNECTED) {

    std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
    client->setInsecure();
 
    HTTPClient https;

    DynamicJsonDocument doc(512);
    JsonObject object = doc.to<JsonObject>();
      
    object["temperature"] = 32;

    String data;
    serializeJsonPretty(object, data);

    Serial.println(data);

    https.begin(*client, serverName);
    https.addHeader("Content-Type", "application/json; charset=UTF-8");       
      
    int httpCode = https.POST(data);

    if (httpCode == 200) {
      Serial.println("POST succeeded with code:");
      Serial.println(httpCode);
      
    } else if (httpCode != 200) {
      Serial.println("POST failed with code:");
      Serial.println(httpCode);

    } else {
      Serial.println("Unknown error");
    }

    String payload = https.getString();
    Serial.println(payload);

    https.end();
  }
  delay(10000);
}

The problem was to have the post method nested inside the if statement instead of having it after adding the headers.
I have modified the code and now it works.

void loop() {

  if(WiFi.status()== WL_CONNECTED) {

    std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
    client->setInsecure();
 
    HTTPClient https;

    DynamicJsonDocument doc(512);
    JsonObject object = doc.to<JsonObject>();
      
    object["temperature"] = 32;

    String data;
    serializeJsonPretty(object, data);

    Serial.println(data);

    https.begin(*client, serverName);
    https.addHeader("Content-Type", "application/json; charset=UTF-8");       
      
    int httpCode = https.POST(data);

    if (httpCode == 200) {
      Serial.println("POST succeeded with code:");
      Serial.println(httpCode);
      
    } else if (httpCode != 200) {
      Serial.println("POST failed with code:");
      Serial.println(httpCode);

    } else {
      Serial.println("Unknown error");
    }

    String payload = https.getString();
    Serial.println(payload);

    https.end();
  }
  delay(10000);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文