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

241 thoughts on “ESP8266: HTTP POST Requests”

  1. Pingback: ESP8266 Arduino: Getting HTTP Response headers | techtutorialsx

  2. Pingback: ESP8266 Arduino: Getting HTTP Response headers | techtutorialsx

  3. hello antepher,
    I have no idea about how to read the data which i send from esp8266 using php. Please give me some examples

    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

  4. hello antepher,
    I have no idea about how to read the data which i send from esp8266 using php. Please give me some examples

    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

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

    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

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

    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

  7. Mateus Bergantini

    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

    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

  8. Mateus Bergantini

    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

    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

  9. hello sir
    i have one question in my mind
    i have a code for temperature sensor with esp 8266 12 e. i set this code to take reading every 30 min
    but when i insert this code to esp it take reading every 27-28 min. i cannot understand that where is the error in code or hardware plz tell me. i can share my code also …thanks
    please reply me

    1. Hi,

      Just with the description you gave I cannot help much :/

      How does the code work? With interrupts? Delays? What is the temperature sensor?

      Best regards,
      Nuno Santos

  10. hello sir
    i have one question in my mind
    i have a code for temperature sensor with esp 8266 12 e. i set this code to take reading every 30 min
    but when i insert this code to esp it take reading every 27-28 min. i cannot understand that where is the error in code or hardware plz tell me. i can share my code also …thanks
    please reply me

    1. Hi,
      Just with the description you gave I cannot help much :/
      How does the code work? With interrupts? Delays? What is the temperature sensor?
      Best regards,
      Nuno Santos

Leave a Reply