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
This entry was posted in ESP8266, IoT, Microcontrollers and tagged , , , , , , , , , , , , . Bookmark the permalink.

97 Responses to ESP8266: HTTP POST Requests

  1. Oak says:

    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

  2. antepher says:

    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

    • Lukas says:

      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

      • antepher says:

        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

        • Lukas says:

          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

          • antepher says:

            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

            • Lukas says:

              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

              • antepher says:

                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

              • Lukas says:

                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

              • antepher says:

                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

          • Gabriel says:

            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. Oak says:

    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. antepher says:

    You’re welcome. Seems an interesting project! Let me know if you discover the problem 🙂

    Like

  5. Shawn Shay says:

    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

  6. Shawn Shay says:

    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

  7. Leo Leow says:

    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

  8. antepher says:

    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

  9. Pingback: ESP8266: Posting JSON data to a Flask server on the cloud | techtutorialsx

  10. Diego Caldas says:

    Can you make a post request to a jsp page? can you give a example?

    Liked by 1 person

    • antepher says:

      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

  11. Aryo says:

    Hi,I want to make an android app that can control rgb led through esp8266 with json format.how do I do that?

    Liked by 1 person

  12. goutham says:

    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

    • antepher says:

      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

  13. goutham says:

    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

    • antepher says:

      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

  14. goutham says:

    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

    • antepher says:

      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

      • goutham says:

        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

        • antepher says:

          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

          • goutham says:

            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

  15. Neil says:

    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

    • antepher says:

      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

  16. wildan2711 says:

    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

  17. antepher says:

    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

  18. Anish Gupta says:

    Hi Lukas
    I am also working on a similar project. Could you please share your project code or if there is any blog you have posted about it

    Liked by 1 person

  19. Kene says:

    Hi. please can you help me with how i can post a picture from the esp8266 to a webServer

    Liked by 1 person

    • antepher says:

      Hi! Sorry but I haven’t yet tried to send pictures / images from the ESP8266 to a webserver. Nevertheless, we’re you able to store it on the ESP8266?

      Like

  20. I’m getting error -3 “send payload failed” when my POST payloads containing a JSON exceed some size around 3000 characters. Do you have any info on that?

    Liked by 1 person

  21. Pingback: Posting ESP8266 weather data to server | causality.io | causality.io

  22. ahmad says:

    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

    • antepher says:

      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

  23. Pingback: Posting ESP8266 weather data to server | DRONEPETS.ORG

  24. vamsi krisha says:

    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

    • antepher says:

      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

      • Vamsi krishna says:

        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

        • antepher says:

          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

  25. JS says:

    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

    • antepher says:

      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

      • JS says:

        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

  26. antepher says:

    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

  27. fmyilmazz says:

    hello i am sending rfid ids to internet page with php. I just sometimes get some mistakes and I do not know how to solve it.
      for example if my internet connection slows down or disconnects, is the nodemcu reconnected? how can I connect again if not connected …
    sometimes dont reading the card ..

    https://github.com/fatihmehmetyy/nodemcurfid

    Liked by 1 person

    • antepher says:

      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

  28. 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

    • antepher says:

      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

  29. Thanks for your appreciation… i simply removed the ‘S’ from the HTTP and it works fine.:).

    Liked by 1 person

    • 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

      • antepher says:

        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

    • antepher says:

      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

  30. Thanks SIr! em working on it. if i found any problem i will let you know !

    Like

  31. 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

    • antepher says:

      Hi!

      You will need to divide your debugging in steps. In this code, are you able to get the values from the sensor and print them, before trying to send them from the server?

      Like

      • 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

  32. Dimaria says:

    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

    • antepher says:

      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

  33. 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

    • antepher says:

      Hi! Sorry, I haven’t been able to identify the problem from your code :/

      Like

      • it’s oky already solved it..!

        Liked by 1 person

        • antepher says:

          Awesome, I’m glad you have been able to solve the problem 🙂

          Wish good luck with your project!

          Best regards,
          Nuno Santos

          Like

          • 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

            • antepher says:

              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

  34. Lingesh says:

    I need to post xml data, can you show sample xml data posting getting xml data

    Liked by 1 person

  35. annelingesh says:

    Hai, I need to post xml data and get xml data as response

    Liked by 1 person

    • antepher says:

      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

  36. mitesh says:

    HI sir nice post
    How to Read Sensor data, and send to Own Domain Web page

    Liked by 1 person

    • antepher says:

      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

  37. Daniel says:

    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

    • antepher says:

      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

  38. Ayush Chand says:

    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

    • antepher says:

      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

  39. Himanshu Saini says:

    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

    • antepher says:

      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

  40. Mitul says:

    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

  41. Can the data be uploaded to webhost domain with the above code( i mean without using php and host computer can we send data from esp8266 to website continously)

    Liked by 1 person

    • antepher says:

      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

  42. Dimak says:

    Thank you very much!

    Liked by 1 person

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 )

w

Connecting to %s