Getting and Posting to API

Hi guys, still beginner so be soft on my low level of knowledge. (Topic is getting data and posting data from ESP8266)
Trying to get data and post data from sensors to api website. But facing a lot of issues (already tried many examples but it never works for me).

WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());

String host = "https://**********.azurewebsites.net/api/Measurements/";

    HTTPClient http;
    http.begin(host);
    Serial.println("A");
    http.addHeader("Content-Type", "application/json");
    http.addHeader("Accept","*/*");
    http.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.59");
    //int httpCode = http.POST("[{\"SensorId\": 1, \"Value\": 55.5}]");
    Serial.println("B");
    int httpCode = http.GET();
    Serial.println("C");
    String payload = http.getString();
    Serial.println("D");
  
   
   Serial.println(httpCode);
   Serial.println(payload);
   http.end();

The result (serial monitor):

02:12:45.517 -> A
02:12:45.517 -> B
02:12:45.517 -> C
02:12:45.517 -> D
02:12:45.517 -> -1
02:12:45.517 ->
02:12:50.484 -> A
....

Not sure what I am doing wrong, but over postman I can get and post data correctly.


Give me please hint what I am doing wrong that HttpCode I am receiving -1 (in arduino)

Thank you!

Which ESP8266 module?

Did you start with File->Examples->ESP8266HTTPClient->BasicHttpClient?

I am using esp8266 d1 mini and Wireless module CH340/CP2102 NodeMcu based on ESP8266 ESP-12E

With examples in Arduino studio I am able to recive data.

01:47:15.773 -> [HTTPS] begin...
01:47:15.773 -> [HTTPS] GET...
01:47:19.054 -> [HTTPS] GET... code: 200
01:47:19.054 -> [{"id":1,"dateOfMeasurement":"2021-08-17T06:37:22+00:00","value":15,"sensorId":1},{"id":2,"dateOfMeasurement":"2021-08-17T06:42:22+00:00","value":16,"sensorId":1},{"id":3,"dateOfMeasurement":"2021-08-24T06:37:22+00:00","value":23.5,"sensorId":1},{"id":4,"dateOfMeasurement":"2021-08-24T07:37:22+00:00","value":23.5,"sensorId":1},{"id":5,"dateOfMeasurement":"2021-08-24T23:46:09.7834126+02:00","value":27.7,"sensorId":1},{"id":6,"dateOfMeasurement":"2021-08-31T00:20:02.1735954+00:00","value":55.5,"sensorId":1}]
01:47:19.101 -> Wait 10s before next round...

Code:

//BasicHTTPSClient.ino

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266HTTPClient.h>

ESP8266WiFiMulti WiFiMulti;

void setup() {

Serial.begin(115200);
// Serial.setDebugOutput(true);

Serial.println();
Serial.println();
Serial.println();

for (uint8_t t = 4; t > 0; t--) {
Serial.printf("[SETUP] WAIT %d...\n", t);
Serial.flush();
delay(1000);
}

WiFi.mode(WIFI_STA);
WiFiMulti.addAP("xxxxxxxxx", "xxxxxx");
}

void loop()
{
// wait for WiFi connection
if ((WiFiMulti.run() == WL_CONNECTED))
{

std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);

client->setInsecure();

HTTPClient https;

Serial.print("[HTTPS] begin...\n");
if (https.begin(*client, "https://xxxxxxxxx.azurewebsites.net/api/Measurements/")) 
{  // HTTPS

  Serial.print("[HTTPS] GET...\n");
  // start connection and send HTTP header
  int httpCode = https.GET();

  // httpCode will be negative on error
  if (httpCode > 0) {
    // HTTP header has been send and Server response header has been handled
    Serial.printf("[HTTPS] GET... code: %d\n", httpCode);

    // file found at server
    if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
      String payload = https.getString();
      Serial.println(payload);
    }
  } else {
    Serial.printf("[HTTPS] GET... failed, error: %s\n", https.errorToString(httpCode).c_str());
  }

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

}

Serial.println("Wait 10s before next round...");
delay(10000);
}

But I have problem with sending data to server.

/*
Rui Santos
Complete project details at Complete project details at ESP8266 NodeMCU HTTP GET and HTTP POST with Arduino IDE | Random Nerd Tutorials

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.

Code compatible with ESP8266 Boards Version 3.0.0 or above
(see in Tools > Boards > Boards Manager > ESP8266)
*/

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

const char* ssid = "xxxxxxx";
const char* password = "xxxxxx";

//Your Domain name with URL path or IP address with path
const char* serverName = "http://xxxxxxxx.azurewebsites.net/api/Measurements/";

unsigned long lastTime = 0;
// 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);

  http.addHeader("Content-Type", "application/json");
  // Data to send with HTTP POST
  String httpRequestData = "[{\"SensorId\": 1, \"Value\": 77.7}]";          
  int httpResponseCode = http.POST(httpRequestData);
 
  Serial.print("HTTP Response code: ");
  Serial.println(httpResponseCode);
    
  // Free resources
  http.end();
}
else {
  Serial.println("WiFi Disconnected");
}
lastTime = millis();

}
}

the monitor report which I get is:

02:03:41.409 -> .......
02:03:45.239 -> Connected to WiFi network with IP Address: 192.168.xxx.xxx
02:03:45.239 -> Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.
02:03:45.845 -> HTTP Response code: 301

"The HTTP response status code 301 Moved Permanently is used for permanent redirecting, "

Using Azure webSite which is accessible from http and https. In this request I am trying over http.

I tried to find template for HTTPs post from Arduino studio but without success.

So I will update question on: during posting getting 301. Dont know why, over postMan I am able to send HTTPS and HTTP request. Here in above code I am posting by HTTP and getting 301 and HTTPS I was not able to figure out how to send.

Update: when on azure I turn off "only https" (only https = false) I will get answer 307.
( HTTP 307 Temporary Redirect redirect status response code indicates that the resource requested has been temporarily moved to the URL given by the Location headers.)

Can I get more somehow more information from answer of request?
By this code I get empty string:

      http.POST(httpRequestData);
      Serial.print("HTTP Response code: ");
      Serial.println(http.getString());

By code bellow I will get just code of answer:

  int httpResponseCode = http.POST(httpRequestData);
  Serial.print("HTTP Response code: ");
  Serial.println(httpResponseCode);

You are being redirected to https::. Try starting with BasicHttpsClient instead of BasicHttpClient.

I tried, but without success.

HTTPS GET is ok:

/**
   BasicHTTPSClient.ino

    Created on: 20.08.2018

*/

#include <Arduino.h>

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

#include <ESP8266HTTPClient.h>

#include <WiFiClientSecureBearSSL.h>


ESP8266WiFiMulti WiFiMulti;

void setup() {

  Serial.begin(115200);
  // Serial.setDebugOutput(true);

  Serial.println();
  Serial.println();
  Serial.println();

  for (uint8_t t = 4; t > 0; t--) {
    Serial.printf("[SETUP] WAIT %d...\n", t);
    Serial.flush();
    delay(1000);
  }

  WiFi.mode(WIFI_STA);
  WiFiMulti.addAP("*******", "********");
}

void loop() {
  // wait for WiFi connection
  if ((WiFiMulti.run() == WL_CONNECTED)) {

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

    HTTPClient https;

    Serial.print("[HTTPS] begin...\n");
    if (https.begin(*client, "https://******.azurewebsites.net/api/Measurements/")) {  // HTTPS

      Serial.print("[HTTPS] GET...\n");
      // start connection and send HTTP header
      int httpCode = https.GET();

      // httpCode will be negative on error
      if (httpCode > 0) {
        // HTTP header has been send and Server response header has been handled
        Serial.printf("[HTTPS] GET... code: %d\n", httpCode);

        // file found at server
        if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
          String payload = https.getString();
          Serial.println(payload);
        }
      } else {
        Serial.printf("[HTTPS] GET... failed, error: %s\n", https.errorToString(httpCode).c_str());
      }

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

  Serial.println("Wait 10s before next round...");
  delay(10000);
}

This works perfectly:

18:42:42.317 -> [HTTPS] begin...
18:42:42.317 -> [HTTPS] GET...
18:42:43.394 -> [HTTPS] GET... code: 200
18:42:43.394 -> [{"id":1,"dateOfMeasurement":"2021-08-17T06:37:22+00:00","value":15,"sensorId":1},{"id":2,"dateOfMeasurement":"2021-08-17T06:42:22+00:00","value":16,"sensorId":1},{"id":3,"dateOfMeasurement":"2021-08-24T06:37:22+00:00","value":23.5,"sensorId":1},{"id":4,"dateOfMeasurement":"2021-08-24T07:37:22+00:00","value":23.5,"sensorId":1},{"id":5,"dateOfMeasurement":"2021-08-24T23:46:09.7834126+02:00","value":27.7,"sensorId":1},{"id":6,"dateOfMeasurement":"2021-08-31T00:20:02.1735954+00:00","value":55.5,"sensorId":1},{"id":7,"dateOfMeasurement":"2021-09-05T00:23:11.4207839+00:00","value":55.5,"sensorId":1},{"id":8,"dateOfMeasurement":"2021-08-24T07:37:22+00:00","value":23.5,"sensorId":1},{"id":9,"dateOfMeasurement":"2021-09-05T02:45:26.6683283+02:00","value":27.7,"sensorId":1},{"id":10,"dateOfMeasurement":"2021-09-05T01:40:53.1303212+00:00","value":55.5,"sensorId":1},{"id":11,"dateOfMeasurement":"2021-09-05T01:46:50.357549+00:00","value":55.5,"sensorId":1},{"id":12,"dateOfMeasurement":"2021-09-05T10:40:01.5129862+00:00","value":55.5,"sensorId":1},{"id":13,"dateOfMeasurement":"2021-09-05T10:40:21.5354758+00:00","value":55.5,"sensorId":1}]
18:42:43.488 -> Wait 10s before next round...

The same HTTPS but as POST, just dont work properly.

/*
  Rui Santos
  Complete project details at Complete project details at https://RandomNerdTutorials.com/esp8266-nodemcu-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.
  
  Code compatible with ESP8266 Boards Version 3.0.0 or above 
  (see in Tools > Boards > Boards Manager > ESP8266)
*/

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

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

//Your Domain name with URL path or IP address with path
const char* serverName = "https://*******.azurewebsites.net/api/Measurements/";

unsigned long lastTime = 0;
// 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)
    {
      std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
      client->setInsecure();
     
      HTTPClient https;

      https.addHeader("Content-Type", "application/json");
      https.addHeader("Content-Length", "65"); 
      https.addHeader("Accept", "*/*");  
     
      String httpRequestData = "[{\"SensorId\": 1, \"Value\": 77.7}]"; 

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

          if (httpCode > 0) 
          {
            // HTTP header has been send and Server response header has been handled
            Serial.printf("[HTTPS] POST... code: %d\n", httpCode);

            // file found at server
            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");
    }
   }
    lastTime = millis();
  }
}

Monitor:

18:47:25.886 -> ..
18:47:26.397 -> Connected to WiFi network with IP Address: 192.168.1.189
18:47:26.397 -> Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.
18:47:30.322 -> [HTTPS] POST...
18:47:31.394 -> [HTTPS] POST... code: 415
18:47:31.394 -> [HTTPS] POST... failed, error: 
18:47:36.409 -> [HTTPS] POST...
18:47:37.438 -> [HTTPS] POST... code: 415
18:47:37.438 -> [HTTPS] POST... failed, error: 
18:47:42.440 -> [HTTPS] POST...

And 415 code is :
The HTTP 415 Unsupported Media Type client error response code

May someone give me hint what I am doing wrong? I have feeling that I am coming from one error code to another :frowning:

Maybe it wants "text/json"?

I tried even that one. ("application/json" even "text/json")
Not sure what can be wrong.
Do you see in the code some issue or do you think that this code should be "ok" and maybe problem is on server side?
(there is not much to break, I tried it over postman and it never get any error with sending json).

Or do you have any working code for posting for HTTPS (insecured).
I am in the dead end.

Maybe it's confused because you told it you were sending 65 characters and only sent 32?

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.