Search code examples
c++arduinonodemcu

Arduino HTTP.post() returns -11


I cannot not find a solution for this problem. Everything worked very well when I tried a month ago, but now, when I launch it, it does not work anymore. The problem occurs when I send http.POST(data); request to the given address, but Serial.println(httpResponseCode); returns -11. I've tested my domain URL on Postman and everything worked there. Thank you for any help.

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#include <DallasTemperature.h>
#include <OneWire.h>
#include <ArduinoJson.h>

#define ONE_WIRE_BUS 4 // D2 pin of NodeMCU

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

// Time configuration
unsigned long lastTime = -300000;
unsigned long timerDelay = 300000;
unsigned long errorThreshold = 5000;

// WiFi configuration
const char *ssid = "myssid";
const char *wifiPassword = "mypass";

// Authentication configuration
const char *username = "myusername";
const char *password = "mypassword";

// Domain name with URL path or IP address with path
const char *authentication = "myurl";

// Functions
int authenticate();

// HTTP
WiFiClient client;
HTTPClient http;
String token = "";

void setup()
{
  // Sets the data rate in bits per second for serial data transmission
  Serial.begin(9600);

  WiFi.begin(ssid, wifiPassword);
  Serial.println("Connecting to WiFi...");

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

  Serial.println();
  sensors.begin();

  Serial.print("Connected to WiFi with IP Address: ");
  Serial.print(WiFi.localIP());
  Serial.print("\n\n");

  while (authenticate() != 200) {
    
  }
}

void loop()
{
  if ((millis() - lastTime) > timerDelay)
  {
    if (WiFi.status() == WL_CONNECTED)
    {
      // ...
    }
    else
    {
      Serial.println("WiFi Disconnected");
      digitalWrite(2, LOW);
      delay(2000);
      digitalWrite(2, HIGH);

      lastTime = millis() - timerDelay + errorThreshold;
    }
  }
}

int authenticate()
{
  // Add headers to Authorization request
  http.begin(client, authentication);
  http.addHeader("Content-Type", "application/json");

  String data = "{\"username\":\"" + String(username) + "\"," +
                "\"password\":\"" + String(password) + "\"}";

  // Send Authorization request
  int httpResponseCode = http.POST(data);
  token = http.getString();

  Serial.println(httpResponseCode);

  return httpResponseCode;
}

I use Visual Code as a code editor. My platformio.ini:

  lib_deps =
         milesburton/DallasTemperature @ ^3.9.1
         bblanchon/ArduinoJson @ ^6.18.4

Solution

  • http.begin(client, authentication);
    

    Please make sure the authentication URL is HTTP and not HTTPS.