ESP8266: HTTP POST Requests

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 at Ebay for less than 5 euros.

If you prefer a video tutorial, please check my YouTube Channel below.

The setup

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

We will need the ESP8266WiFi.h, so we can connect the ESP8266 to a WiFi network, and the ESP8266HTTPClient.h, which makes available the methods needed to perform the POST request.

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

In the Arduino setup function, we will start by initializing a serial connection, so we can output the results of our program.

Serial.begin(115200);

After that, we will take care of connecting the ESP8266 to a WiFi network, so later we can send the HTTP request. To do so, we only need to call the begin method on the WiFi extern variable, passing as first input the name of the network (SSID) and as second the password. Note that, in the snippet below, I’m using placeholder strings that you should replace by your network credentials.

For a detailed tutorial on how to connect a ESP8266 to a WiFi network, please check here.

WiFi.begin("yourSSID", "yourPASS"); 

To finish the setup function, we will poll the status of the WiFi connection until it is established. We are using a polling approach here for simplicity, since we can only start doing the HTTP POST requests after the connection to the WiFi network is established. Naturally, in a real application, we should take in consideration that there might be some issue trying to connect to the network and that polling might not be the best approach for the requirements.

The complete setup function can be seen below.

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");

  }

}

The main code

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

First of all, we need to define an object of 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 will call the begin method on the http object and pass the URL that we want to connect to and make the HTTP 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 used in the code snippet implements a dummy REST API for testing and prototyping).

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

Next, we can define headers for the request 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 it is important to check for error handling.

Take in consideration that, if the value is greater than 0, it corresponds to a standard HTTP code. If this value is lesser than 0, it corresponds to a ESP8266 error, related with the connection. You can check the list of possible errors here.

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

We will print both the received payload and the HTTP code.

Serial.println(httpCode);
Serial.println(payload);

To finish, we need to call the end method on the http object to guarantee that the TCP connection is closed. This is very important to free the resources.

http.end();

The final code is shown bellow. To handle any possible WiFi connection errors, we will include a validation of the connection status before making the request. We will also add a 30 seconds delay between each iteration of the Arduino loop, to avoid a constant polling of the server.

Note that, to keep the code simpler and focus on the main subject of sending the HTTP POST request, we did not check if the httpCode variable 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 MuleSoft 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 application receiving HTTP POST from ESP8266
Figure 1 – Output of the MuleSoft 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.

Output of the ESP8266 POST Request program, on the Arduino IDE serial monitor
Figure 2 – Output of the POST requests.

To avoid having to setup your own server to test the ESP8266 code, you can simply send the request to the testing API suggested in the previous section.

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 code section:

http.writeToStream(&Serial);

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

Technical details

  • ESP8266 libraries: v2.3.0.
  • Operating system: Windows 8.1

Related Posts

242 thoughts on “ESP8266: HTTP POST Requests”

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

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

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

    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

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

    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

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

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

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

    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

      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.

        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

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

    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

      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.

        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

  9. 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 ?

    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

      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.

  10. 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 ?

    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

      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.

Leave a Reply

Discover more from techtutorialsx

Subscribe now to keep reading and get access to the full archive.

Continue reading