ESP8266: HTTP POST Requests

The objective of this post is to explain how to do POST requests from an ESP8266, using the Arduino IDE and the ESP8266 libraries.


Introduction

The objective of this post is to explain how to do POST requests from an ESP8266, using the Arduino IDE and the ESP8266 libraries. All the tests shown here were performed on a NodeMCU board, which you can find here at eBay for less than 5 euros.

If you prefer a video tutorial, please check the video bellow on my YouTube Channel.


The setup

First, we need to include some libraries, which should be available after the installation of the ESP8266 libraries for the Arduino IDE.

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

In the setup function, we will just initialize the Serial connection, in order to print the results of our application. Besides that, we need to establish a connection to an AP (Access Point), so the ESP8266 will be able to make the HTTP Requests. The code is specified bellow.

void setup() {

  Serial.begin(115200);                 //Serial connection
  WiFi.begin("yourSSID", "yourPASS");   //WiFi connection

  while (WiFi.status() != WL_CONNECTED) {  //Wait for the WiFI connection completion

    delay(500);
    Serial.println("Waiting for connection");

  }

}

For more details on how to connect to a WiFi network, check this previous post.


The main code

In this section, we will analyze the code needed in the main loop function to perform the POST request. We will break the code and analyze the most relevant parts step by step, but the final code is summarized at the end of the section.

First of all, we need to declare an object of the class HTTPClient, from which we will call various methods to prepare the headers and content of the request, send it and check for the result. We will call this object simply “http”.

HTTPClient http;

After that, we call the begin method on the http object and pass the URL that we want to connect to and make the post request. In this case, I’m sending the post request to an application running on my local network, which is why I’m sending it the format seen bellow (Host IP:Port/Path).

http.begin("http://192.168.1.88:9999/hello");

Nevertheless, we can send the request to a website by specifying it’s domain name, as seen bellow (the destination website specified implements a dummy REST API for testing and prototyping).

http.begin("http://jsonplaceholder.typicode.com/users");

Next, we can define headers with the addHeader method. In this case, we are specifying the content-type as “text/plain”, since we will just send a simple string in the body.

http.addHeader("Content-Type", "text/plain");

The body of the request is specified as a parameter when calling the POST method on the HTTPClient object. In this case, we will simply send a string saying “Message from ESP8266”. The return value of this method corresponds to the HTTP response code and thus is important to check for error handling.

int httpCode = http.POST("Message from ESP8266");

We can now get the payload by calling the getString method, which will return the response payload as a string.

String payload = http.getString();

In the end, we need to call the end() method on the object to guarantee that the TCP connection is closed. This is very important to free the resources.

http.end();

Just to handle any possible WiFi connection errors, we will include a validation of the connection status before making the request. For debugging purposes, we will print both the response payload and the HTTP code.

The final code is specified bellow. To keep the code simpler and focus on the main subject, we did not check if the httpCode is less than zero, which indicates an error in the connection. Nevertheless, we should do so in the final code of an application.

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

void setup() {

  Serial.begin(115200);                                  //Serial connection
  WiFi.begin("yourSSID", "yourPASS");   //WiFi connection

  while (WiFi.status() != WL_CONNECTED) {  //Wait for the WiFI connection completion

    delay(500);
    Serial.println("Waiting for connection");

  }

}

void loop() {

 if(WiFi.status()== WL_CONNECTED){   //Check WiFi connection status

   HTTPClient http;    //Declare object of class HTTPClient

   http.begin("http://192.168.1.88:8085/hello");      //Specify request destination
   http.addHeader("Content-Type", "text/plain");  //Specify content-type header

   int httpCode = http.POST("Message from ESP8266");   //Send the request
   String payload = http.getString();                  //Get the response payload

   Serial.println(httpCode);   //Print HTTP return code
   Serial.println(payload);    //Print request response payload

   http.end();  //Close connection

 }else{

    Serial.println("Error in WiFi connection");   

 }

  delay(30000);  //Send a request every 30 seconds

}

 

Testing the code

In the context of this tutorial, I was sending the post requests to a mule application running in a machine on my local network. Just to illustrate the result, figure 1 shows the output of incoming requests on the console of the development environment. As can be seen in the bottom right, it is printing the “Message from ESP8266” string we defined early.

Mulesoft receiving post from ESP8266

Figure 1 – Output of the mule application that is receiving the POST requests.

Figure 2 shows the HTTP codes and response payloads for the POST requests. In this case, I defined a simple “Message received” string as response to the requests.

ESP8266 HTTP Post response

Figure 2 – Output of the POST requests.


Final Notes

As an alternative, the begin method used before can be called with other sets of parameters, as can be seen in the specification of the HTTPClient class. For example, we can pass the host IP, port and path as 3 different parameters, instead of a single string, amongst many other options.

The HTTPClient class also has a method to simplify debugging of a response to the request. So, if we want to print the response payload to the serial port, we can just call the writeToStream method and pass as argument a pointer to the Serial port, that we initialized before in the setup function. So, the call bellow is an alternative to the getString method used in the example:

http.writeToStream(&Serial);

These are just 2 alternative implementation examples. The HTTPClient class many other useful methods not used in this tutorial. You can check them here.


Technical details

ESP8266 libraries: v2.3.0.

Advertisements

113 Replies to “ESP8266: HTTP POST Requests”

  1. Is it possible to do this kind of POST request from arduino UNO board (not directly from ESP8266)?

    I need to read a card ID with an RFID reader (attached to an arduino board) and send it to a django server via POST. I have found several examples on how to put the ESP8266 as server, but I don’t want it. I just want to send the data to a django server which has a few REST webservices available.

    Is it possible with ESP8266? if not, how can I do that?

    Thank you!

    Liked by 1 person

    1. Do you mean the nodemcu which can be board independent or the esp8266 which gives connectivity to the arduino because putting the if you’re using the esp8266 it’s the arduino that’s the server.

      Like

      1. Hi,

        NodeMCU is the name of a generic board that has a ESP8266 inside it.

        So, when you are “programming a NodeMCU”, in fact, you are programming a ESP8266.

        The Arduino is another board. Most Arduino boards don’t have WiFi support.

        So, it is not possible to send a POST request directly from an Arduino board that doesn’t have WiFi connectivity.

        However, you can connect an Arduino board to an ESP8266 board (for example, a nodeMCU), establish a serial connection with it, and send a command to the ESP8266, that then is able to send the HTTP POST request,

        Hope this clarifies. 🙂

        Best regards,
        Nuno Santos

        Like

        1. Worked fine..After 2 days, again tried to post request it does not working.Where the NodeMCU serial monitor is showing http payload error “-1” I am unable to understand, what I am doing wrong.

          Like

          1. Hi!

            when you mention after two days, did you leave the system working for two days and after that it stopped working? Or did you test the same code again after two days?

            Best regards,
            Nuno Santos

            Like

  2. In the example of this post, we are using the ESP8266 as a client and not as a server, so you can send data to a Django server (or any other application that can receive HTTP requests). It should work fine with the REST webservices. Just check what type of content the Django server is expecting to receive (it can be, for example, JSON) and specify it in the addHeader function.

    You can’t do this kind of POST request using only an Arduino UNO board, since it can’t connect to the Internet. So, you will always need to use the ESP8266 to send the actual HTTP POST to the server.

    Nevertheless, you can use the Arduino board to read the data from the RFID reader, send that data to the ESP8266, which can then send it to the server. The easiest way to make the Arduino and the ESP8266 talk is by a Serial connection.

    If you follow this approach, you need to take in consideration that the ESP8266 operates at 3.3V and the Arduino UNO at 5V, so you need to do some voltage level conversion in order to not damage the ESP8266.

    The other option, which I would recommend, is to remove the Arduino UNO from the equation and use just the ESP8266. In this case, you use the ESP8266 to read the data from the RFID reader and then send it to the Django Server.

    It will depend on the RFID reader you are using, but most probably there will be a library for the ESP866 to work with it easily. Just be careful because if the RFID reader works at a voltage greater than 3.3V, you will also need some voltage level conversion.

    With this second option, you have less hardware (which is cheaper) and you don’t need to have the time delay of the Arduino sending the data to the ESP8266.

    Like

    1. Hi antepher 🙂
      I want send data from my arduino NANO to my website. I have serial connection between arudino and esp. I understand your comment that I must upload code from this article to esp. How can I send data from my arduino to esp.

      Liked by 1 person

      1. Hi Lukas 🙂 well, to do so you just need to check the basic Arduino serial communication functions.

        On the Arduino Nano side, you need to send the data, using the Serial.write or the Serial.print functions. Example here:
        https://www.arduino.cc/en/Serial/Write

        On the ESP8266 side, you need to read the data, with Serial.read. Example:
        https://www.arduino.cc/en/Serial/Read

        You can check bellow the available functions for the Arduino side. I don’t know if all of them are implemented in the ESP8266, but the main ones should be.
        https://www.arduino.cc/en/reference/serial

        Important stuff to take in consideration:
        – The ESP8266 works with 3.3V and the Arduino with 5V. You need to do some level conversion to not damage the ESP.
        – The baud rates need to be the same when you start the Serial connection (by calling Serial.Begin). I’ve had some troubles in the past using some baud rates on the ESP8266, such as 9600. A value that works for sure is 115200.

        Also, depending on how robust your application needs to be, you may want to implement a simple serial protocol, to guarantee that you don’t loose or misinterpret data exchanged by the devices. You can check an old post that explains how to do it (parts 1 and 2):
        https://techtutorialsx.com/2015/12/06/serial-communication-data-structuring-pt-2/

        Nevertheless, if you are starting now with serial communication, then I would recommend you to first learn the basics and then worry about this more advanced things.

        Like

        1. Thank you antepher for info. I used Serial.write() on my Arduino NANO to send information to my ESP, and Serial.readString() on my ESP to receive incoming data and it work perfect ! 🙂 I have another question. How can I send GET/POST from my website using php and receive data on my ESP ?

          Liked by 1 person

          1. I’m glad it worked fine 🙂

            The easiest way to do it is by setting a simple webserver on the ESP8266, to get incoming data. You can check bellow how to do it:
            https://techtutorialsx.com/2016/10/03/esp8266-setting-a-simple-http-webserver/

            In that example, I’m sending the HTTP request from a web browser. I your case, you should send it from the PHP application.

            One important thing to take in consideration is that when you connect to a WiFi network with the ESP, you will get a local IP, which is only valid in that network. So, to be able to send a HTTP request to the ESP, your PHP application should be running on the same network as the ESP8266.

            If not, you will have to configure your router to do portforwarding, which means it will need to be able to receive requests on its public IP and forward them to one of the internal IPs of the network, the one assigned to the ESP8266. Nevertheless, this is a more advanced topic and may subject your network to security issues.

            My recommendation is that you test it locally, with both the ESP8266 and the PHP application in the same network, unless you have prior experience with the procedure.

            The mentioned post is an introductory tutorial, the ESP supports many more functions related to receiving HTTP requests. Check some more tutorials:
            https://techtutorialsx.com/2016/11/19/esp8266-webserver-controlling-a-led-through-wifi/
            https://techtutorialsx.com/2016/10/30/esp8266-webserver-receiving-get-requests-from-python/
            https://techtutorialsx.com/2016/10/22/esp8266-webserver-getting-query-parameters/
            https://techtutorialsx.com/2016/10/15/esp8266-http-server-serving-html-javascript-and-css/
            https://techtutorialsx.com/2017/03/26/esp8266-webserver-accessing-the-body-of-a-http-request/

            Hope it helps.
            Best regards

            Like

            1. Good, I will test it locally, and if everything will be good i will have configure my router to do portforwarding, because is important for me to send data from my website which is in other network. I want two options on my one ESP. I want put data to my website and receive data from website to my ESP. I understand that when I want send data to ESP it must be set as client, and when I want receive data from website, I must configure webserwer on my ESP?

              Liked by 1 person

              1. Let us know if you succeed 🙂

                Yes, I think the easiest way is by doing what you mention. To receive data from the website you set some URLs on your ESP and receive and treat HTTP requests, so it is working as webserver. When you want to send data from the ESP, you use it as a client by sending HTTP requests.

                Naturally, you have other options. You could have socket communication, which operates at a lower level than HTTP, or use MQTT, which is another communication protocol. But for what you are trying to achieve (communicating with a PHP server) I think HTTP is the easiest way.

                Like

              2. I configured my router to do portforwarding, and it works perfect 🙂 I received data on ESP from my website. I used JQuery library in my website to send HTTP GET request to the IP address(ESP). But I have one problem. I used server.arg(i) on ESP to get value of the parametr, and this return value in string. I must send to Arduino NANO value in int. So I did it:
                int value = server.arg(i).toInt();
                Serial.write(value);
                On Arduino NANO i used Serial.read() but it didn’t work correct. I got different value. So my question is how can I send value int from ESP, and receive in Arduino NANO?

                Liked by 1 person

              3. Awesome news, I’m happy it all worked fine 🙂

                That function should work as long as the string is a number. Maybe the string also has letters or something? You can try to print the output of server.arg(i) and check if it is only a number or if it has some more content.

                If it has characters or something other than only the number you are trying to convert, you can use the Substring function to get the part you want:
                https://www.arduino.cc/en/Tutorial/StringSubstring

                Hope it helps

                Like

          2. Man I need to do pretty much the same thing. Could you share your code to give me some light? Do I need to program the Arduino separately from the esp? Thanks!

            Liked by 1 person

  3. Thank your for you detailed explanation!!

    Probably, my problem is the header of the request. All other things (voltages, serial connections, RFID reader, …) are under control 🙂

    I didn’t know that ESP8266 could read from RFID sensors, but I can do taht in this project, because it need to be improved with 2 simultaneous readers and a SD card storage, so the best option will be to centralize everything in the Arduino CPU.

    Thanks again for your response, I will take a look to the headers and check all the code again.

    Liked by 1 person

  4. I keep getting a “-1” returned for httpCode

    Here is my code

    void loop() {
    //
    if(WiFi.status()== WL_CONNECTED){ //Check WiFi connection status
    HTTPClient http; //Declare object of class HTTPClient

    http.begin("http://192.168.43.162:80/iot/post.php?"); //Specify request destination
    Serial.println("Connected to HTTPClient");
    http.addHeader("Content-Type", "text/plain"); //Specify content-type header
    int httpCode=http.POST("id=13&value=46.79"); //Send the request
    String payload = http.getString(); //Get the response payload
    Serial.println(httpCode); //Print HTTP return code
    Serial.println(payload); //Print request response payload
    http.end(); //Close connection

    }
    //
    else{
    Serial.println("Error in WiFi connection");
    }

    delay(30000); //Send a request every 30 seconds
    }

    Liked by 1 person

    1. Hi,

      My recommendation is to try to test things separately first if you haven’t done it yet

      You can try to reach the destination address http://192.168.43.162:80/iot/post.php? from another computer in your local network. The firewall of the machine where the webserver is running may be refusing the connection, thus resulting in an error in the ESP8266.

      There may also be some problem with the logic on the webserver that is triggering an internal error and no response is returned to the ESP.

      Just another note, it seems that you are trying to send query parameters id=13&value=46.79 in the body of the post request. Query parameters are passed in the URL, so if you just want to send that information, you should send a GET request in the following format:
      http://192.168.43.162:80/iot/post.php?id=13&value=46.79

      You can check in more detail how to send GET requests from the ESP in another post:
      https://techtutorialsx.wordpress.com/2016/07/17/esp8266-http-get-requests/

      It may also be a problem from the ESP. Were you able to use the code of this tutorial successfully to reach the example website? http://jsonplaceholder.typicode.com/users

      Like

      1. Hi! The suggestion remains the same, test your code separately to try to isolate the error.

        First of all, are you trying to reach a HTTPS (with an S at the end) website? If so, it is not possible with this code.

        Can you make a request to your destination website using a tool such as postman?

        Best regards,
        Nuno Santos

        Like

    2. if somebody still needs the answer to data question,
      you have to set

      http.addHeader(“Content-Type”, “application/x-www-form-urlencoded”);

      instead of plain/text

      http.addHeader(“Content-Type”, “text/plain”);

      Liked by 1 person

  5. I keep getting a “-1” for httpCode any ideas?


    void loop() {
    //
    if(WiFi.status()== WL_CONNECTED){ //Check WiFi connection status
    HTTPClient http; //Declare object of class HTTPClient

    http.begin("http://192.168.43.162:80/iot/post.php?"); //Specify request destination
    Serial.println("Connected to HTTPClient");
    http.addHeader("Content-Type", "text/plain"); //Specify content-type header
    int httpCode=http.POST("id=13&value=46.79"); //Send the request
    String payload = http.getString(); //Get the response payload
    Serial.println(httpCode); //Print HTTP return code
    Serial.println(payload); //Print request response payload
    http.end(); //Close connection

    }
    //
    else{
    Serial.println("Error in WiFi connection");
    }

    delay(30000); //Send a request every 30 seconds
    }

    Liked by 1 person

  6. Hi, i couldn’t download the library in Github in ZIP file and i tried manually to save it, however, i have fatal error while compiling:
    fatal error: include/wl_definitions.h: No such file or directory

    #include “include/wl_definitions.h”.

    Could you please help

    Liked by 1 person

  7. Hi! Have you tried to follow the installation guide of the ESP8266 libraries via boards manager of the Arduino IDE? They include the http client and Wifi libraries used in this post.

    The easiest way is to follow the guide in the post bellow (check Arduino IDE configuration section):
    https://techtutorialsx.wordpress.com/2016/02/28/esp8266-uploading-code-from-arduino-ide/

    I never installed them manually. I think the best way is to do it via boards manager because all the dependencies are handled for you.

    Like

    1. Hi! I’m not familiarized with the technology, so I never tested it. But have you tried this code without success?

      If you can provide me with a website that uses this technology I can try to make a quick test.

      Like

    1. Hi! It depends on the architecture you want to implement, but I would say something like this would work fine:

      – You need to have the ESP listening for incoming HTTP requests, so you can receive commands to control your RGB LED. You can check here how to configure the ESP to work as a simple HTTP web server.
      https://techtutorialsx.wordpress.com/2016/10/03/esp8266-setting-a-simple-http-webserver/

      – Then, if you want to use JSON, you need to be able to parse incoming JSON data. You can check how to do that in the ESP here.
      https://techtutorialsx.wordpress.com/2016/07/30/esp8266-parsing-json/

      Naturally, you will need to implement the functions to control the LED and the android app.

      Hope it helps, let me know if you need more help.

      Like

  8. Hi.
    Presently i am able to send http POST requests and receive the request in a php page which i hosted on other system using nodemcu esp8266 12-E board.Now I connected mpu6050 sensor to nodemcu and receive the mpu6050 sensor values in the php file like i received the previous request but i am not getting the real time sensor readings.Can u provide me the correct coding.

    Liked by 1 person

    1. Hi!
      Sorry I don’t know if I understood your problem. You are sending the POST request from a nodemcu board and you have a system that has a PHP page, right?

      Are you getting the correct values from the sensor on the nodemcu, before actually sending them to the PHP page? If not, that should be the first debug step: getting the values and printing them to the serial port, to check if they are ok.

      Then, how are you sending the values in the POST request? In the body of the request or in the URL? Also, are you sending just raw values (directly the values you get from the sensor) or using some type of protocol, such as JSON or XML?

      Then, is your PHP code expecting to receive the sensor values in the format you are sending from the nodemcu?

      There are too many variables, you should divide the debugging in steps to isolate the cause of your problem.

      Like

  9. Hi,Thanks for replying.

    Yeah exactly i have a system with a PHP page where i want to send the http POST requests.I am able to send normal messages to the page.My task is to send the sensor values which is connected to nodmcu development board continuously to the php page using arduino IDE. Previously i have the send the sensor values to the system using a firmware called devicehive cloud. There is a html page where it receives requests from the nodemcu to which mpu6050 sensor is connected and values are displayed but it is taking requests very slowly at a rate of 10s approximately.I wanted to send continuous request for every 1 to 2seconds where i can do it from arduino ide using your code.Can u provide me a similar type of example code like any sensor so that i can send the sensor values continuously. Ultimately i wanted to set the sensor to a threshold where it can give an alert when it experiences a motion beyond certain threshold set in the code.

    Liked by 1 person

    1. Hi!

      Well, I cannot give you an exact code because you should send the content in a format that your PHP page will understand, and I don’t know what format it uses.

      Are you posting the exact value you get from the sensor? Like, if the sensor returns “10”, the body of your POST request is “10”? Or are you using a protocol like JSON?

      The interval you have to send the readings of the sensor is defined by you, right? In pseudo code, you should do something like:

      While (1){
      x = getSensorValue();
      sendHTTPrequest(x);
      delay(interval);
      }

      If the requests are taking to much time, maybe there is some problem in the PHP code. Can you measure the execution time of the code in the PHP page, between receiving the request from the Nodemcu and answering the request?

      Also, if you want something near real time, you would have better performance by opening a socket to the server, maintaining it open and sending the data in a simpler protocol. HTTP has much more overhead in the quantity of data sent and you are opening and closing a connection each time you send a request, which makes it slower.

      You can also use something like MQTT, for example.

      Like

  10. Hi
    I want to send the sensor readings to the PHP page in other system.Is there any such type of example such that the sensor values are displayed in the webpage via sending POST requests using arduino ide.

    Liked by 1 person

    1. Hi. I usually use Python for implementing the back-end systems, so I don’t have any example with PHP.

      I have an example on how to send data to a Python Flask application. You may be able to adapt it:
      https://techtutorialsx.com/2017/01/08/esp8266-posting-json-data-to-a-flask-server-on-the-cloud/

      I think it will be hard to find a specific example in the web that sends sensor readings to a PHP page via POST and shows the values in a webpage.

      I think the best way is to divide the problem in peaces and find examples for each one. That way you can figure out how each peace of your final system works and then link everything together.

      Like

      1. Hi

        The above code which u provided where we sending an arbitrary message (“Hello World”),Can’t we edit the code in such a way that sensor sends a POST request to the php page in other sysytem or server whenever it exceeds certain tolerance.I have no idea using MQTT .Can u help me to sort it out

        Liked by 1 person

        1. Hi! Yes, you just need to pass the value to the function. I think a simple conversion to string is enough. But are you having difficulty with the logic of the program or with the HTTP functions?

          int x = getSensorValue();

          if (x> thresholdValue){

          HTTPClient http; //Declare object of class HTTPClient

          http.begin(“yourSite”); //Specify request destination
          http.addHeader(“Content-Type”, “text/plain”); //Specify content-type header

          http.POST(String(x));
          String payload = http.getString();

          http.end(); //Close connection

          }

          You can check more on string conversions here:
          https://www.arduino.cc/en/Reference/StringConstructor

          Like

          1. Hi
            I want to get the sensor readings from mpu6050 to nodemcu and it has to send a POST request.
            Currently i am able to send an arbitrary message from Nodemcu to PHP page on a computer but i need to get the sensor readings from mpu6050 to Nodmcu.

            Liked by 1 person

  11. Hi! Thanks for creating this — your tutorial have been very helpful.

    I keep on getting a -1 as the httpCode from the server. Here’s what my code looks like:

    void loop() {
    if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    http.begin(“http://pi.local:8000/planner/test-light/”);
    Serial.println(“Connected to HTTPClient”);
    http.addHeader(“Content-Type”, “text/plain”);
    int httpCode = http.POST(“test”);
    String payload = http.getString();
    Serial.println(httpCode);
    Serial.println(payload);
    http.end();
    }
    delay(5000);
    }

    I’ve tried making a post request from another computer using CURL and it works fine. Any idea what the problem could be?

    I saw your GET post request and that worked fine.

    Thanks for any help!

    Liked by 1 person

    1. Hi! Thanks for your feedback, I’m glad you are finding the content useful 🙂

      One thing that may be the reason for the issue is that you are exposing your webserver using mdns. Or at least it is what it seems, since you have a .local domain.

      Can you find what is the actual IP of your server and change the pi.local by the IP in the begin method? That would be my first suggestion. It may worked fine with CURL because your computer was able to do mdns resolution and the ESP8266 was not.

      For the Get request example, did you use the website provided in the post or did you already use the pi.local? If it worked with the pi.local, then the problem should be other.

      Let me know if it helps

      Like

  12. Hi, thanks for the like! It means so much.. But I have a question related to this post. How would I POST a form-data, by setting http.addHeader(“Content-Type”, “multipart/form-data”); ? How would I set the payload? Thank you!

    Liked by 2 people

  13. Hi! You’re welcome 🙂 Well I never tried doing a post request using that content type.

    But I think it should work if you send a string with the content respecting the format you need for that content type. That string is passed to the POST method.

    For example, when I’m sending application/json content, I just pass a string with the JSON to the POST method (example bellow).
    https://techtutorialsx.com/2017/01/08/esp8266-posting-json-data-to-a-flask-server-on-the-cloud/

    Like

    1. Hi! I never ran into that issue but I don’t recall having tried a request with a payload so big.

      I’ve been taking a quick look to the source file where that error code is generated but I didn’t find any limitation in the size on the code, such as a limiting variable or so:
      https://github.com/esp8266/Arduino/blob/2d9e7676309506da9be6e9bf0e1e7a3d7356d8f5/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.cpp

      My guess is that it may be exceeding any limit on the lower level API calls.

      Also from this thread, it seems like a work around is sending the data in chunks, although it requires using the WiFi client (same as socket connection) for sending the data in parts.
      https://github.com/esp8266/Arduino/issues/1872

      But my suggestion is that you ask around the GitHub page for checking if someone ran into the same issue.

      If I find some more information meanwhile I will share here.

      Best regards,
      Nuno Santos

      Like

      1. I’ve checked that link you provided while doing some research on this topic but couldn’t find a solution.

        Currently I’m sending multiple posts as it was easier for me on this project but in the future I’ll look deeper into this. If I find anything I’ll post here.

        Thanks a lot for your answer!

        Liked by 1 person

  14. Hi, i am using NodeMcu ESP8266 with current sensor. i just want to use it as access point and when i put SSID an Password it will connect to the local router ..when it connect i want to stream my real time data on webpage.. please help me

    Liked by 1 person

    1. Hi! Do you need help with each part?

      For setting the ESP8266 as an access point you can check this tutorial:
      https://techtutorialsx.com/2017/04/25/esp8266-setting-an-access-point/

      How do you need the password and ssid information to be sent to the ESP8266? By an HTTP request, for example, or with the user manually inputting it?

      In either cases, after receiving the password and SSID, you need to then change from soft AP mode to station mode and connect to the access point.

      In order to send the information in real time the best way is by using sockets. Unfortunately I don’t have any example about it, but you can check here:
      https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiClient/WiFiClient.ino

      In your case, if you need the data in Real Time, using sockets you can remove the overhead of the HTTP requests and leave the socket open. I need that example can help getting you started, but you will need to adapt it for your needs.

      Hope it helps you getting started.

      Best regards,
      Nuno Santos

      Like

  15. can i post data from one esp 8266 to other esp8266 through the http?? If yes suggest me a solution. i am using one esp8266 as a server and other one as a client.

    Liked by 1 person

    1. Hi! Yes you should be able to send data from one ESP8266 to another using HTTP.

      The architecture is as you said: one of them needs to be working as server and the other as client.

      In this tutorial, you have the code for the client ESP8266.

      In the tutorial bellow, you have the code for your ESP8266 server:
      https://techtutorialsx.com/2016/10/03/esp8266-setting-a-simple-http-webserver/

      I’m assuming that both ESPs will be connected to a WiFi network, although you could put one of them working as soft AP in order to avoid the need for a router.

      So, upon running the code of the server, you should get an IP in the serial monitor, which corresponds to the IP of your server ESP8266. That is the IP that you should use in the requests performed on the client ESP8266.

      so, instead of http://192.168.1.88:8085/hello in the begin function, you should have
      http://your_ESP_IP:80/your_server_route.

      Hope this helps.
      Best regards,
      Nuno Sants

      Like

      1. Hi antepher thanks for your reply. The above link you mentioned is sending data to the webpage thorugh esp8266. I want to send data from one esp8266 to other esp8266 through http or any other methods. I set one esp as a server and other one is client. i connected both of them through softapIP. The thing i want here is just to take the data from my client and send to the server and to display the data. I dont want to display the data in webpage.

        Liked by 1 person

        1. Hi! It is being showed in a webpage because on that example we were accessing it through a web browser. So, in the example of the link, our client was the web browser.

          In your case, instead of doing the request using the browser, you should do the request using your ESP acting as client (the code is the one from the post we are commenting on). So, instead of the information being displayed in the browser, it will be received by your client ESP8266.

          One important thing to note is that the ESP that is acting as a server doesn’t need to know which type of client is sending the request. So, your ESP will simply respond to the request as long as it is correctly formatted, either if the client is a browser, a python or Java program, a command line CURL command or another ESP8266.

          So the server code is suitable for what you wan’t to achieve. Naturally, you need to adapt it for the data you are working with, but the rest should work fine.

          Hope this clarifies your doubts.

          Best regards,
          Nuno Santos

          Like

  16. Thank you for the great article

    I want send data from mutiple nodeMcu(client) to one Nodemcu(server).
    One client and one server works very well

    But multiple client not works very well

    can you pls help ?

    Liked by 1 person

    1. Hi! Thanks for the feedback 🙂

      How much delay do you have between each request of the clients? If you are sending a lot of requests without delay, maybe the ESP is not being able to process them all.

      Also, are you freeing the resources on both the clients and server with a call to the end function?

      Some client may be leaving resources opened on the server side.

      By the way, which are the problems you are experiencing?

      Best regards,
      Nuno Santos

      Like

      1. Thank you very much for your response.

        First, I am not so good at English. And also not so good at coding.

        I have three nodemcu. (two clients, one server, and two clients Includes thermistor sensor )
        Two clients have a distance. And Sometimes sending data to servers is enough.

        Unfortunately. i Can barely understand coding, I have no idea how to start.

        I searched for almost two weeks, but I couldn’t find a similar example.

        I need your help.

        Thank you.

        Like

  17. You’re welcome 🙂

    To be honest it will be hard to help without a prior knowledge on coding.

    The Arduino environment is very easy to get started, but it is important that you try t get some basic programming knowledge before going to a system like you mentioned, which is already considerably complex.

    My recommendation is that you try to learn the basics of the Arduino language before tackling more advanced topics such as using the ESP8266 WiFi. There are plenty of resources around the web about it.

    Although it is easy to find working code for the ESP8266 that we upload and works, it will be difficult to tweak it to suit your needs without some basic programming experience.

    Best regards,
    Nuno Santos

    Like

    1. Hi! I’ve not been working for a while with the ESP8266 WiFi, but from the source files of the WiFi library I think it should automatically reconnect, or at least there’s a function that seems to allow that:

      https://github.com/esp8266/Arduino/blob/9dcc580aef055bd1c5226655abd5266c6049a54f/libraries/ESP8266WiFi/src/ESP8266WiFiSTA.h

      My recommendation is that you try to test it separately from your RFID program. Basically, just set a simple program that connects to wifi, makes HTTP requests periodically to some website and prints them to the serial port.

      When setting the WiFi, just call the following function, by passing the value true as input (the function is the one I mentioned from the source files):
      bool setAutoReconnect(bool autoReconnect);

      Then disconnect the router for a while and connect it again and check if the ESP reconnects and starts making the requests again.

      I’m not sure it will work, but it seems that it should by the API.

      Not that the problem you are facing may not be caused by the WiFi but rather by some problem with your server.

      If you emulate some requests to your php webpage with another program (for example, writing a simple Python script to send HTTP test requests to it) how does it behave? Do you also get mistakes?

      I’ve seen a fair share of people having problems with the whole system and think that it was caused by the ESP and in fact it was the server that had some bugs.

      You may also have some problems with the RFID code. If are experiencing mistakes and not the absence of data, it may not be caused by the WiFi.

      When designing systems that have many parts communicating, the best approach is to test every part independently first before connecting the whole system. You should only start connecting everything when you are confident that each individual part is working as expected. Otherwise it will be a debugging nightmare.

      Hope this helps.
      Best regards,
      Nuno Santos

      Like

  18. my “httpCode” returns -1 .. means it isn’t sending data to website..here is a code if i made something wrong to the code please guide me. Thanks!..
    #include
    #include
    void setup() {
    Serial.begin(115200); //Serial connection
    WiFi.begin(“ZONG MBB-E5573-C840”, “77423072”); //WiFi connection
    Serial.println(“Setup iniated”);
    while (WiFi.status() != 3) { //Wait for the WiFI connection completion
    delay(500);
    Serial.println(“Waiting for connection”);
    Serial.print(“WIFI STATUS : “);
    Serial.println(String(WiFi.status()));
    }
    Serial.println(String(WiFi.status()));
    }

    void loop() {
    HTTPClient http;
    //String Data = “x=” + (String)distance + “&y=” + (String)MAX_HEIGHT + “&z=0”;
    String Data = “x=Jungli&y=Billi&z=Wild”;
    http.begin(“https://testingblahblah.000webhostapp.com/IOTCON.php”);
    http.addHeader(“Content-Type”, “application/x-www-form-urlencoded”);
    int sent = http.POST(“x=Jungli&y=Billi&z=Wild”);
    Serial.println(sent);
    String httpPayload = http.getString();
    Serial.println(httpPayload);
    if(sent > 0)
    {
    Serial.println(“Message has been sent”);
    } else {
    Serial.println(“unable to send data”);
    }
    delay(20000);
    }

    Liked by 1 person

    1. Hi! You are trying to reach an HTTPS (not the S from secure after HTTP).

      This code is not suitable for using with HTTPS websites. When you contact a HTTPS website, you need to deal with stuff such as digital certificates and encryption.

      In the past, there was some support for that on the ESP8266, but it was pretty limited and didn’t allow to validate a whole certificate chain, we could simply hardcode the sha fingerprint of the certificate of the client we were trying to contact, which was not that much useful in terms of security.

      I’ve not been using the ESP8266 for a while, so I’m not sure if things have evolved since then. But at least, they still have the original HTTPS example:
      https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/HTTPSRequest/HTTPSRequest.ino

      If you really need HTTPS, my recommendation is that you take a look at the ESP32, the “evolution” of the ESP8266. It handles HTTPS very well and is able to validate the whole certificate chain.

      Hope it helps.

      Best regards,
      Nuno Santos

      Like

    1. Hi sir! One more thing i want to ask you is that i am actually working on a project to send ultrasonic sensor values to website, for that i tested your code for passing raw data to website and it works fine.. now i am confused how to make some changes to tested code regarding ultrasonic sensor.. i am posting my ultrasonic code here.that you could help me out to re-write this code according to sensor. I will be very thankful..

      int trigger=13;
      int echo=12;

      void setup()
      {

      Serial.begin(9600);
      pinMode(trigger,OUTPUT);
      pinMode(echo,INPUT);
      }

      void loop()
      {
      float time=0,distance=0;
      digitalWrite(trigger,LOW);
      delayMicroseconds(2);
      digitalWrite(trigger,HIGH);
      delayMicroseconds(10);
      digitalWrite(trigger,LOW);
      delayMicroseconds(2);
      time=pulseIn(echo,HIGH);
      distance=time*340/20000;

      Serial.print(“Distance:\n”);
      Serial.print(distance);
      Serial.print(“cm\n”);
      Serial.print(“Distance:\n”);
      Serial.print(distance/100);
      Serial.print(“m\n”);
      delay(1000);
      }

      Like

      1. Adapting the code should be simple. In the original example you shared, instead of using the x and y variables in the POST method, you can build a string of data with your distance variable from this code.

        Just as a note, if you want you can send the content of the POST request as JSON, since the ESP8266 can handle JSON very well.

        A good library is the ArduinoJson.

        Best regards,
        Nuno Santos

        Like

    2. Hi! I’m glad it is working for you 🙂 Just take in consideration that once you remove the S from the HTTPS you are now longer sending the content encrypted.

      Thus, all the things you are sending to your website are in plain text and can be easily intercepted by an attacker. Please take this in consideration if you are sending sensitive data.

      Like

  19. Hell sir! i am having trouble to send ultrasonic sensor values to my webserver, seems like ultrasonic is not taking reading , and it sends o value to server , is there a problem of insufficient current for ultrasonic sensor or there is another problem plz help here is a Code. if any mistake found plz let me know.
    .NOTE: i check the simple code for ultrasonic and it works perfect.

    #include
    #include
    #define trigger 12
    # define echo 13
    float timex = 0;
    float distance = 0;
    float max_height = 0;
    float extra_space = 4.00;

    int TANK_SPECIAL_ID = 1;

    void setup() {

    pinMode(trigger,OUTPUT);
    pinMode(echo,INPUT);
    Serial.begin(115200);
    delay(5000);
    WiFi.begin(“AndroidAP”, “lovely12”);

    Serial.println(“Setup Initiated\n”);

    while (WiFi.status() !=3) {
    delay(500);
    Serial.println(“Waiting for connection”);
    Serial.print(“WiFi Status : “);
    Serial.println(String(WiFi.status()));
    }
    Serial.println(String(WiFi.status()));
    }

    void loop() {
    HTTPClient http;
    int Percentage = 0;
    digitalWrite(trigger,LOW);
    delayMicroseconds(2);
    digitalWrite(trigger,HIGH);
    delayMicroseconds(10);
    digitalWrite(trigger,LOW);
    delayMicroseconds(2);
    timex = pulseIn(echo,HIGH);
    distance = timex * 340 / 20000;

    if (max_height == 0) {
    Serial.println(“Setting max_height”);
    max_height = distance;
    Serial.println(“max_height configured.. 5 seconds delay”);
    delay(5000);
    Percentage = -1;
    Serial.print(“MAX HEIGHT: “);
    Serial.println(max_height);
    } else {
    int revVal = int(distance / max_height * 100);
    Percentage = revVal – 100;
    Serial.print(“Current Ratings: “);
    Serial.print(distance);
    Serial.print(” cm”);
    Serial.print(” | Percentage: “);
    Serial.print(Percentage);
    Serial.println(” %”);

    }
    if(distance > -1) {

    String Data = “x=” + String(Percentage) + “&y=” + String(max_height) + “&z=” + String(TANK_SPECIAL_ID);
    http.begin(“http://zaptraff.atwebpages.com/IOT/IOTCON.php”);
    http.addHeader(“Content-Type”, “application/x-www-form-urlencoded”);

    int sent = http.POST(Data);
    Serial.print(“Request val:”);
    Serial.println(sent);
    //String httpPayload = http.getString();
    //Serial.println(httpPayload);
    if(sent > 0) {
    Serial.println(“Data has been sent”);
    } else {
    Serial.println(“unable to send data”);
    }
    }

    delay(1000);
    }

    Like

      1. yeah! i separated the code of ultrasonic sensor when i change the board from Generic ESP8266 to arduino UNO than it gives the values to serial monitor but when i switch the board to generic and try to run whole code than it’s not working.. i also tried to give external 5v power for ultrasonic sensor but nothing works. i don’t get what’s the real problem.

        Like

  20. Hi,
    I’m trying to send a String which is my name to a php file in the localhost then using POST method then simply print it to the browser here is my Arduino sketsh and PHP file:

    #include
    #include

    char ssid[]= “AT-4GLTE-E5172AS-22-FC8C8”;
    char pass[]= “J1BY051TB4E”;
    String url=”http://192.168.1.2/NodeMcu_tests/hellow.php”;
    String name=”Dimaria”;

    void setup() {
    Serial.begin(9600);
    delay(500);
    connect_to_wifi();

    if(WiFi.status() ==WL_CONNECTED)
    {
    HTTPClient http;
    http.begin(url);
    http.addHeader(“Content-Type”,”text/plain”);
    http.POST(“name=”+name);
    http.end();

    }

    else

    Serial.println(“Erreur WiFi !!!!!!!!”);

    }

    void loop() {

    }

    void connect_to_wifi()
    {

    Serial.print(“Connecting ………..”);
    delay(500);
    WiFi.disconnect();
    WiFi.begin(ssid,pass);

    while(WiFi.status() !=WL_CONNECTED)
    {
    delay(500);
    Serial.println(“…..”);

    }
    Serial.println(“Successfully connected”);

    }

    php file:

    but unfortunatly I have got not thing printed but Undifined reference to name.

    thanks for your attention……

    Liked by 1 person

    1. Hi!

      Sorry wordpress probably doesn’t allow you to post php source code in comments :/

      Nonetheless, I’m assuming the “undefined reference to name” you mention is on the PHP side right?

      Unfortunately I don’t know much about PHP so I cannot help you with that part of the code.

      Nonetheless, my recommendation is that you test things separately before going for the end to end.

      Have you tried to send the request to the PHP page from a tool such as Postman to confirm that your backend is working correctly?

      If it still gives you that problem, then the problem is on your backend you need to focus on debugging the backend code.

      Just a note, you shouldn’t share the credentials of your wifi network in comments on the web, due to security reasons 🙂

      Best regards,
      Nuno Santos

      Like

  21. i’ been facing problem since last week that i can’t get ultrasonic readings
    when i connect with my esp8266 wifi module ,everytime it gives 0cm reading.My

    both hardwares work perfectly if i connect them individually. is there any logical problem please help Sir 😦

    Liked by 1 person

          1. Thanks! but i have been facing new problem as my recent solution was to connect Gpio pin for data trasnmission that act as bridge between arduino board and esp8266. so simply i connect esp8266 GPIO2 pin with ultrasonic sensor echo pin and that echo pin was connected by arduino board digital pin 2 and i directly connected the trig pin. it was working fine. but sometime i get stuck with constant 0 reading and sometime constant 100 reading i can’t find what the actual problem is.. am i doing right by connecting only one echo pin with esp8266 Gpio pin or do i need to connect both echo and trig pin to other Gpio pin
            Note: i have only two GPIO pin in esp8266- esp-01 one is GPIO0 for flashing and uplaoding data and another one is for trasnmitting data GPIO2 . plesae help what should i do . code are the same as above didn’t change anything thanks

            Liked by 1 person

            1. Hi! Sorry, unfortunately I’ve never worked with the ultrassonic sensor on the ESP, I can’t give you much assistance :/

              But check if yo have all the gnds connected, it may be the source of your problem.

              If it is possible for your project, you can also move everything to an ESP board that exposes all the pins of the ESP8266. The ESP-01 is very limiting in that aspect, but there are plenty of ESP8266 boards out there with lots of pins you can use, without the need for the arduino board.

              Like

    1. Hi!

      Sorry I haven’t yet worked with XML in the ESP8266.

      I usually use JSON because it has much less overhead. Maybe you can find some XML libraries for the Arduino environment around the web.

      Best regards,
      Nuno Santos

      Like

    1. Hi! Thanks for the feedback 🙂

      Well that’s a too generic topic that can be tackled in many ways. 🙂

      What do you mean by Own Domain Web page?

      Regarding the sensor, you need to read your measurements (most likely periodically) and send them as the body of your post request.

      You need to choose a suitable data format. I typically use JSON, is lightweight and you have plenty of parsers.

      Hope it helps,
      Nuno Santos

      Like

        1. Hi!

          As long as your backend is able to receive HTTP Post requests, you should be able to use this code to send data to it, assuming that continuously is without a persistent connection and at a rate supported by the ESP and the backend.

          Best regards,
          Nuno Santos

          Like

  22. Hi antepher, fantastic post.

    I have a question:
    I was able to successfully do an HTTP POST request to httpbin.org.
    httpbin.org replies with code 200 and the following:
    Response from server is{
    “args”: {},
    “data”: “PHESS test sentence”,
    “files”: {},
    “form”: {},
    “headers”: {
    “Accept-Encoding”: “identity;q=1,chunked;q=0.1,*;q=0”,
    “Connection”: “close”,
    “Content-Length”: “19”,
    “Content-Type”: “text/plain”,
    “Host”: “httpbin.org”,
    “User-Agent”: “ESP8266HTTPClient”
    },
    “json”: null,
    “origin”: “71.94.131.30”,
    “url”: “http://httpbin.org/post”
    }

    How would I be able to retrieve that data on another network from another computer?

    Again, thanks a lot!

    Liked by 1 person

    1. Hi Daniel,

      Thank you very much for the feedback, I’m glad it is working for you 🙂

      What do you mean by retrieving that data from another network on another computer?

      Like having a local web server serving content for your ESP?

      Let me know a little bit more about what you are trying to do to see if I can help 🙂

      Best regards,
      Nuno Santos

      Like

  23. Hello Nuno,

    I am trying to POST sensor data from one Esp 8266 to another. Here is the code from the client(station).
    http.begin(“http://192.168.4.1:80/w”);
    I am getting wdg resets when POSTing to the server, On debugging it shows,
    [hostByName] Host: 192.168.4.1 is a IP!
    :ref 1

    Here is my client code snippet. Still can’t find out the problem,…

    // Static network configuration
    IPAddress ip(192, 168, 4, 4);
    IPAddress gateway(192, 168, 4, 1);
    IPAddress subnet(255, 255, 255, 0);

    WiFiClient client;

    void setup() {
    ESP.eraseConfig();
    WiFi.persistent(false);
    Serial.begin(115200);
    delay(500);
    pinMode(ESPLED, OUTPUT);
    WiFi.mode(WIFI_STA);
    ESP.wdtDisable();
    ESP.wdtEnable(WDTO_8S);
    WiFi.config(ip, gateway, subnet);
    WiFi.begin(ssid, password);
    Serial.println(“”);
    while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(“.”);
    counter++;
    }
    }

    void sendHttpRequest(String Content)
    {
    HTTPClient http;
    http.begin(“http://192.168.4.1:80/w”);
    http.addHeader(“Content-Type”, “text/plain”);
    int k= http.POST(“Lvl = 2134123”);
    Serial.println(k);
    http.writeToStream(&Serial);
    http.end();
    }

    Here is my server code

    void handle_feed() {
    String t = server.arg(“Lvl”);
    Serial.print(t);
    server.send(200, “text/plain”, “Received Level”);
    }

    void handleRoot() {

    server.send(200, “text/plain”, “Resolved by dns”);
    }

    void setup() {
    pinMode(TRIGGER_PIN,OUTPUT);

    Serial.begin(115200);
    WiFi.mode(WIFI_AP);

    Serial.println(“** SETUP ACCESS POINT **”);
    Serial.println(“- disconnect from any other modes”);
    WiFi.disconnect();
    Serial.println(“- start ap with SID: “+ String(ssid));
    WiFi.softAP(ssid, password);

    IPAddress myIP = WiFi.softAPIP();
    Serial.print(“- AP IP address is :”);
    Serial.print(myIP);
    Serial.println(“** SETUP SERVER **”);
    Serial.println(“- starting server :”);
    server.on(“/”, handleRoot);
    server.on(“/w”, handle_feed);
    server.begin();
    if(MDNS.begin(“myesp”))
    {
    Serial.println(“DNS Started”);
    }
    MDNS.addService(“http”, “tcp”, 80);
    }

    void loop() {

    server.handleClient();

    }

    Liked by 1 person

    1. Hi!

      That’s weird, never experienced that problem.

      Why are you changing the watchdog values? You are trying to increase the time before it fires right? Does it also not work if you remove those calls?

      How much time does it take to trigger the watchdog? Is it immediate, like it resets as soon as it makes the request, or does it take a while, like the program is hanging somewhere?

      If you test your server isolated, like making a request from a tool such as Postman, does it answer in reasonable time or does it hang?

      If it is hanging, then it may be your server not responding fast enough, leaving the client hanging and eventually triggering the watchdog.

      Also, if you try sending the same client request to a dummy website, like this:
      https://jsonplaceholder.typicode.com/
      does it also reset?

      For now, it seems to be the best option trying to check where the problem lies, since looking at the end to end system will be harder. So my suggestion is that you try to check if the problem is on the client or on the server.

      Another suggestion is to post an issue on the git hub pages of the ESP8266 Arduino libraries, so maybe someone has already also experienced something similar.

      Hope this helps you going in the right track 🙂

      Best regards,
      Nuno Santos

      Like

  24. Hi
    If I host a local server on my laptop. How can I request to it through nodemcu. Or more precisely what will be the IP address to my localhost server?

    Liked by 1 person

    1. Hi!

      It should be the local IP of your laptop in the network.

      Depending on the framework you are using you may have to explicitly bind the server to the local IP.

      If you are on windows, you should be able to get the IP with a ipconfig command, and on linux with a ifconfig command, on the command line.

      Note that the ESP8266 needs to be connected to the same network of your laptop.

      Hope it helps.

      Best regards,
      Nuno Santos

      Like

  25. Thanks for a great post. Can I use this to send data from nodemcu to the firebase cloud functions using json format. If so can you please reply with a small code for the same. Just the main part will be enough. Thanks for the help.

    Liked by 1 person

    1. Hi! Thanks for the feedback 🙂

      Unfortunately I never had the chance to test it against firebase :/ I don’t know how fire base works, but if it uses regular HTTP you should be able to.

      Here is a tutorial on how to work with json and the esp8266:
      https://techtutorialsx.com/2016/08/10/esp8266-encoding-json-messages/

      Note however if firebase only works with HTTPS, then you will not be able to reach it using the code shown here.

      At the time I’ve been using the ESP8266, it didn’t manage HTTPS very well, due to the need to validate the whole certificate chain.

      As alternative, if you really need HTTPS and still have plenty of resources to develop your application, my suggestion is to take a look at the ESP32:
      https://techtutorialsx.com/2017/11/18/esp32-arduino-https-get-request/

      Best regards,
      Nuno Santos

      Like

    1. Hi!

      Not sure if I understood your question.

      You can use this code to send a HTTP post request (with data) to a server.

      A HTTP web server may be implemented with a lot of technologies, doesn’t need to be php.

      Your host may not be a computer, for instance, your host can be another ESP8266 and you can use this code to send data to it.

      Nonetheless, you need some device to host your server / website.

      When you mean continuously, do you mean like periodic, or like “real time” with a persistent connection (real time here is an abuse of language since it has another meaning in the world of embedded systems, but is a term commonly used)?

      If you need a persistent connection, then it is better to switch to something like using a direct socket connection.

      Hope this helps 🙂

      Like

    1. Hi! Thank you very much for the feedback 🙂

      Yes you should be able to use both HTTP request methods on your program.

      When you mention at the same time, I’m assuming that it is in the same program, but one request after another, right?

      Best regards,
      Nuno Santos

      Like

  26. Hey Antepher,
    thanks for sharing with us this project!
    Im having a problem with a simple project i am trying to do, I hope you can help me-

    my MySQL DB(Cpanel server) include a table “Alerts” that have- day,hour(4 different hours 9,14,19,22),cell,status(if the button pressed). we try to light a led when the time “now” equals to the alert schedule.
    in the sending data -what i thought is that after the button is being pressed it will send 0/1 to the server to change the “status”.
    in the receiving data- i need to get the cell the day and the hour to light the button.

    I read and tried so many things but i’m not even sure i make a connection with the Cpanel server
    this is what i tried- and it says i have a connection to the server but it doesn’t display my string

    Thank you very much!

    #include
    #include
    #include
    #include
    const char server[] = “shaniru.mtacloud.co.il”;

    const char* MY_SSID = “Idok”; ///hot-spot
    const char* MY_PWD = “12345678”;

    WiFiClient client;

    void setup()
    {
    Serial.begin(115200);
    Serial.print(“Connecting to “+*MY_SSID);
    WiFi.begin(MY_SSID, MY_PWD);
    Serial.println(“going into wl connect”);

    while (WiFi.status() != WL_CONNECTED) //not connected, …waiting to connect
    {
    delay(1000);
    Serial.print(“.”);
    }
    Serial.println(“wl connected”);
    Serial.println(“”);
    Serial.println(“Credentials accepted! Connected to wifi\n “);
    Serial.println(“”);
    }

    }

    void loop() {

    // Wait a few seconds between measurements.
    delay(2000);

    //prefer to use float, but package size or float conversion isnt working
    //will revise in future with a string fuction or float conversion function
    // int IfTake=0;
    Serial.println (“IfTake”);

    Serial.println(“\nStarting connection to server…”);
    // if you get a connection, report back via serial:
    if (client.connect(server, 80)) {
    Serial.println(“connected to server”);
    WiFi.printDiag(Serial);
    int ifTake= 585;
    int ido=123;
    String data = “ido=”
    + (String) ido
    + “ifTake=” +(String) ifTake;

    //change URL below if using your Sub-Domain
    client.println(“POST gettingData.php HTTP/1.1”);
    //change URL below if using your Domain
    client.print(“Host: shaniru.mtacloud.co.il\n”);
    client.println(“User-Agent: ESP8266/1.0”);
    client.println(“Connection: close”);
    client.println(“Content-Type: application/x-www-form-urlencoded”);
    client.print(“Content-Length: “);
    client.print(data.length());
    client.print(“\n\n”);
    client.print(data);
    client.stop();

    Serial.println(“\n”);
    Serial.println(“My data string im POSTing looks like this: “);
    Serial.println(data);
    Serial.println(“And it is this many bytes: “);
    Serial.println(data.length());
    delay(2000);
    }

    }

    void printWifiStatus() {
    // print the SSID of the network you’re attached to:
    Serial.print(“SSID: “);
    Serial.println(WiFi.SSID());

    // print your WiFi shield’s IP address:
    IPAddress ip = WiFi.localIP();
    Serial.print(“IP Address: “);
    Serial.println(ip);

    // print the received signal strength:
    long rssi = WiFi.RSSI();
    Serial.print(“signal strength (RSSI):”);
    Serial.print(rssi);
    Serial.println(” dBm”);
    }

    Liked by 1 person

    1. Hi! You’re welcome, and thanks for the feedback 🙂

      Unfortunately I never worked with that feature with CPanel, so I cannot be of much assistance.

      Nonetheless, I can recommend some things that may help.

      First of all, are you sure that the feature of CPanel that you are trying to use is reachable by HTTP? Or does it use any other protocol?

      If it is HTTP, is it regular HTTP or is it secure HTTP (HTTPS)? If it is HTTPS, then your code should not work because it is not handling the secure related stuff, such as encryption, validating certificates, etc..

      If it is plain HTTP, then my recommendation is that you use the ESP HTTP Client API from this post. It should be less error prone than using sockets (WiFiClient is the same as using sockets).

      Also, assuming that the CPanel can be reached by HTTP, you can first try to send the request from a tool such as Postman, which is for sure a reliable HTTP client. If it also doesn’t work with postman, then most likely there is something wrong with the data that you are sending to the server or some problem with the server.
      https://www.getpostman.com/

      Hope this can help you debugging your application 🙂

      Best regards,
      Nuno Santos

      Like

    1. Hi!

      Sorry, unfortunately I never worked much with PHP, so I’m also not aware how to do it.

      But PHP is widely used, so I’m sure you will be able to find lots of information around the web on how to receive HTTP post requests.

      Note that receiving requests from the ESP8266 or from any other application should work the same way, so you can more easily find the PHP information you need.

      Hope this helps.

      Best regards,
      Nuno Santos

      Like

  27. Hi antepher
    This tutorial is really interesting, I think it might be what I need , However I don’t Know how to apply it to what I need, I simply need to send the information I type on a textbox on a html webpage (I have created a server with the NodeMCU) through the server, to be displayed by the serial monitor, Would you be able to help me with that ?

    I am stuck between getting the html script variables to talk to the arduino IDE variables .

    Liked by 1 person

    1. Hi!

      Thank you very much for the feedback, I’m glad you found the tutorial interesting 🙂

      In that case, this tutorial won’t help you because here the ESP8266 is acting as a client, that is making a post request to a remote server.

      In your case, what you need is to setup the ESP8266 to work as a server (as you mentioned, you already set the nodemcu to work as a server).

      I’m assuming that you are serving the HTML from the ESP8266, which means that you already set up a route to serve the page.

      Additionally, you will need to setup another route to receive the content from the HTML webpage checkbox.

      So, what you need is to add is the remaining code to your HTML page so, when you fill in the text box and probably click in some button, the content of the text box is submitted to the ESP server

      So, in fact, it will be the HTML page that will do a HTTP request to your ESP8266 server (and not the other way around like you were trying to apply).

      Regarding how you do that, it pretty much depends on how you want to send the data. You can directly submit it as form data, you can use some format such as json, etc..

      I have a tutorial for the ESP32 that does something very similar to what you are trying to achieve, although you need to adapt the code for your web page needs.

      Note that the async HTTP web server library that I’m using on the ESP32 should also work on the ESP28266 with minor changes on the includes.
      https://techtutorialsx.com/2018/01/06/esp32-arduino-http-server-serving-html-and-javascript/

      Hope this helps getting you on the right path 🙂

      Best regards,
      Nuno Santos

      Like

  28. Hello!

    First of all, thanks for sharing such a good level of information, certainly is helping a lot of people,like me.

    Im working in a similary project, can you help with some problens?

    My system is basicaly like this: RFID->Arduino->Esp8266-01->MySQL->WebPage

    My only issue is sending data from esp to my web page, wich as treat and manipulate my data base them actualize the information and show in a web page.

    Could you give some light to some?

    My degree in engineering depend on this hahaha

    Thank you

    Liked by 1 person

    1. Hi!

      You are welcome, and thanks for the feedback, I’m very happy to know these examples are useful 🙂

      Regarding on how you “send data” to the web page, it’s important understand a couple of things before I can give a suggestion.

      Who is serving your webpage? Is your ESP8266 serving the webpage, or is another computer in the network and you want your webpage to read information from the ESP?

      Also, how frequently does your data change? Do you want it to be “real time”, or do you want to periodically ask for that information to the ESP?

      Let me know a little bit more so I can try to help 🙂

      Also, wish you good luck with your degree, I’m sure you will make it 🙂

      Best regards,
      Nuno Santos

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s