ESP32: HTTP POST Requests

The objective of this tutorial is to explain how to make HTTP POST requests using the ESP32 and the Arduino environment support. We will use the HTTPClient.h library to hide the low level implementation details.


Introduction

The objective of this tutorial is to explain how to make HTTP POST requests using the ESP32 and the Arduino environment support. We will use the HTTPClient.h library to hide the low level implementation details.

So, we don’t need to worry about building the HTTP protocol on top of a socket connection, since we will have methods available to deal with that. For sending HTTP GET requests with the same library, please check this previous tutorial.

Important: At the time of writing this tutorial, the HTTPClient.h library had just been merged to the ESP32 libraries for the Arduino environment. So, you will most likely need to update to for the latest code available. Check here how to do it.


The code

The initial portion of the code will be the same needed for the HTTP GET requests with the ESP32. So, we will start by including the libraries needed, declaring some global variables to hold the WiFi network credentials and, in the Arduino setup function, connect to the WiFi network. If you need a detailed guide on how to connect to a WiFi network with the ESP32, please check this previous tutorial.

Important: At the time of writing, there was the need for making a small delay before calling the WiFi.begin function, for connecting to the WiFi network. Before updating the ESP32 libraries, this delay was not needed. Nevertheless, this may eventually not be needed anymore when you test the code, so you can play with this delay and check if the ESP32 can connect to the WiFi network without it. You may also need to increase it if you experience problems with the connection.

#include <WiFi.h>
#include <HTTPClient.h>

const char* ssid = "yourNetworkName";
const char* password =  "yourNetworkPassword";

void setup() {

  Serial.begin(115200);
  delay(4000);   //Delay needed before calling the WiFi.begin

  WiFi.begin(ssid, password); 

  while (WiFi.status() != WL_CONNECTED) { //Check for the connection
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }

  Serial.println("Connected to the WiFi network");

}

After the initialization code, we will go for the main loop, where we will write the code needed for making the HTTP POST requests. We will declare an object of class HTTPClient, which makes available the methods needed for handling the HTTP protocol.

Then, we call the begin method on the previously declared object and pass as input the URL for the website where we want to make the POST request. We will use a fake online REST API website, suitable for testing. You can check it here.

HTTPClient http;

http.begin("http://jsonplaceholder.typicode.com/posts"); //Specify destination for HTTP request

After that, we will call the addHeader method, which will allow us to specify the HTTP request headers. In this case, we will define the content-type header, which specifies the media type of the body of the request [1] we will send. We will specify it as “text/plain“, since we are only going to send a simple textual message, without any particular format.

As can be sen bellow, this method receives as first input the header we want to specify, and as second input its value.

http.addHeader("Content-Type", "text/plain"); //Specify content-type header

Now, to send the actual HTTP request, we call the POST method, passing as input the body content of the request. We will send a simple message just for illustration purposes. Since we are contacting a fake API, it will always accept out content.

This method will return the HTTP response code, which we will store in a variable. Note that if the value returned is lesser that zero, then an error occurred on the connection. If it is greater than zero, then it’s a standard HTTP code.

int httpResponseCode = http.POST("POSTING from ESP32"); //Send the actual POST request

Since we stored the HTTP response code, we will use it for error handling, as we will see the code bellow. If our request was successfully sent, we will get the HTTP answer by calling the getString method. Then, we will print the answer and the HTTP code. In case of error, we will print a informative message.

if(httpResponseCode>0){

    String response = http.getString();  //Get the response to the request

    Serial.println(httpResponseCode);   //Print return code
    Serial.println(response);           //Print request answer

}else{

    Serial.print("Error on sending POST: ");
    Serial.println(httpResponseCode);

}

Finally, we will call the end method on our http object to free the resources. This call is important and mustn’t be forgotten. Check the full source code bellow, which already includes this call. It also includes a delay between each request, and a conditional block to check if we are still connected to the WiFi network before sending a request.

#include <WiFi.h>
#include <HTTPClient.h>

const char* ssid = "yourNetworkName";
const char* password =  "yourNetworkPassword";

void setup() {

  Serial.begin(115200);
  delay(4000);   //Delay needed before calling the WiFi.begin

  WiFi.begin(ssid, password); 

  while (WiFi.status() != WL_CONNECTED) { //Check for the connection
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }

  Serial.println("Connected to the WiFi network");

}

void loop() {

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

   HTTPClient http;   

   http.begin("http://jsonplaceholder.typicode.com/posts");  //Specify destination for HTTP request
   http.addHeader("Content-Type", "text/plain");             //Specify content-type header

   int httpResponseCode = http.POST("POSTING from ESP32");   //Send the actual POST request

   if(httpResponseCode>0){

    String response = http.getString();                       //Get the response to the request

    Serial.println(httpResponseCode);   //Print return code
    Serial.println(response);           //Print request answer

   }else{

    Serial.print("Error on sending POST: ");
    Serial.println(httpResponseCode);

   }

   http.end();  //Free resources

 }else{

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

 }

  delay(10000);  //Send a request every 10 seconds

}


Testing the code

The procedure for testing the code is the same as usual. Just upload the code for the ESP32 using the Arduino IDE and open the serial monitor to check the output. You should get something similar to figure 1.

ESP32 HTTP POST Request

Figure 1 – Output of the program to send HTTP POST Requests with the ESP32.

Note that a HTTP 201 code is returned, which corresponds to “created” [2]. This means a resource was created in the server, which is the expected simulated behavior since we are doing a POST.

So, the answer includes an ID, telling us the identifier of the new resource. Since this is a fake testing website, nothing is happening on the backend and this is a simulated response, so all the following POST requests will return the same ID. Also, there is no checking for the structure of the content we are sending.


Related Posts


References

[1] https://www.tutorialspoint.com/http/http_header_fields.htm

[2] https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

Advertisements
This entry was posted in ESP32 and tagged , , , , , , . Bookmark the permalink.

4 Responses to ESP32: HTTP POST Requests

  1. ARJ says:

    Consider publishing your blog as a book !

    Liked by 1 person

    • antepher says:

      That’s a very nice idea, would be nice to put these tutorials on paper (or e-paper 🙂 ) and structure them to help people getting started and evolve to more complex topics.

      But although I like the idea very much, I have a really busy daily job and unfortunately it doesn’t leave me much time for a project as big as that :(.

      Maybe in a not so distant future I get more time for blogging / writing and can start something like that!

      Like

  2. animesh sachan says:

    a very good example of http post method in esp32. I have a different problem, I want upload data on the server in the form of zipped files. or text file. can you write an example for this purpose?

    Liked by 1 person

    • antepher says:

      Hi! Thank you very much for the feedback 🙂 Just to confirm, you want to create the .zip file or the text file on the ESP32 and upload it to a remove server right?

      I haven’t played with none of them yet. Zip files won’t probably be easy, but maybe creating a text file will be possible. At least with MicroPython we can create text files in the File System, so it may be possible to send them via HTTP POST.

      On Arduino I haven’t yet played with the File System, I will try to take a look as soon as I have some time and share the results here.

      Like

Leave a Reply

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

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s