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: HTTP PUT request – techtutorialsx

  2. Pingback: ESP8266 Arduino: HTTP PUT request – techtutorialsx

      1. No, no it will not. The article is made for the ESP8266 board and the libraries are for that board in particular. And even if there were compatible drivers, arduino boards don’t have any way of connecting to the internet by themselves.

Leave a Reply

%d bloggers like this: