ESP32: HTTP GET Requests

The objective of this post is to explain how to perform simple HTTP GET requests using the ESP32 and the Arduino environment. To do so, we will use the HTTPClient.h library.


Introduction

The objective of this post is to explain how to perform simple HTTP GET requests using the ESP32 and the Arduino environment. To do so, we will use the HTTPClient.h library.

Important: Please note that at the time of writing this post, this library had just been merged with the Github master code, as can be seen here. So, you will most likely need to update your version of the ESP32 Arduino support libraries. You can check here the instructions on how to do it.

Note that you may have to both open Git GUI and run the get.exe file as administrator, on Windows, for the changes to take effect. If everything works fine, under the examples menu of the Arduino IDE, you should have an entry for HTTPClient examples. You can also view the examples at Github.

Although before the HTTPClient library was made available we could perform HTTP requests, this was more complex since we would have to deal with all the HTTP protocol over socket connections, as can be seen in this example. Fortunately, this library will hide much of the complexity and only expose easy to use functions.

So, in our simple example, we will connect to a WiFi network and do some HTTP GET requests to a fake online rest API website. You can explore this website here.

The code bellow is based on one of the basic examples provided with the HTTPClient library, which I encourage you to try.


The code

First of all, we will need to include the libraries for both connecting to a WiFi network and to perform the HTTP requests. You can check in more detail how to connect to a WiFi network with the ESP32 in this previous post.

We will also need to store the credentials of the WiFi network, so we can connect to it on the setup function. To do so, we will declare two global variables, as can be seen bellow. Note that you should change the values by your network credentials.

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

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

Now, in the setup function, we will open a serial connection, for printing debugging messages, and connect to the WiFi network. Please check the mentioned previous post if you need a detailed explanation on the procedure. Please maintain the delay before the WiFi.begin call, to guarantee that everything done in the background by the libraries starts fine. At the time of writing, if we didn’t include the delay, the connection to the WiFi network would fail most of the times.

void setup() {

  Serial.begin(115200);
  delay(4000);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }

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

}

We will send the HTTP requests on the Arduino main loop. First of all, we declare an object of class HTTPClient. This class will make available a lot of methods that will help us work with the HTTP functionalities without needing to worry with the low level implementation details. You can check the header file for a list of those methods.

HTTPClient http;

After that, we will call the begin method on the previously declared object, passing as a string parameter the URL where we want to perform the HTTP request. As we said, we are going to send the request to a testing website. You can directly access the URL in a web browser to check the expected content to be returned.

http.begin("http://jsonplaceholder.typicode.com/comments?id=10"); //Specify the URL

Now, to send the request, we just call the GET method on the http object. This methods receives no arguments and returns the HTTP code of the request, which we will store on a variable for error handling. Note that codes lesser than 0 are error codes from the library (you can check the list here) and values greater than zero are standard HTTP return codes.

So, if the code is greater than zero, we will print both the HTTP code returned and the response to our request. We get the response by calling the getString method, which receives no arguments and returns a string with the response. Otherwise, we will print an error message.

if (httpCode > 0) { //Check for the returning code

        String payload = http.getString();
        Serial.println(httpCode);
        Serial.println(payload);

}else {

      Serial.println("Error on HTTP request");

}

Finally, we will need to call the end method, to ensure the resources are freed. It’s important that we don’t forget this call.

http.end(); //Free the resources

You can check the full source code bellow, which already includes a small delay between each request. Also, before each request, we are checking if we are still connected to the WiFi network.

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

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

void setup() {

  Serial.begin(115200);
  delay(4000);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }

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

}

void loop() {

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

    HTTPClient http;

    http.begin("http://jsonplaceholder.typicode.com/comments?id=10"); //Specify the URL
    int httpCode = http.GET();                                        //Make the request

    if (httpCode > 0) { //Check for the returning code

        String payload = http.getString();
        Serial.println(httpCode);
        Serial.println(payload);
      }

    else {
      Serial.println("Error on HTTP request");
    }

    http.end(); //Free the resources
  }

  delay(10000);

}

 

Testing the code

To test the code, just upload it with the Arduino IDE and open the serial monitor. You should get an output similar to figure 1. Note that we are getting an HTTP 200 code, which corresponds to an OK code.

ESP32 HTTP GET request

Figure 1 – Output of the HTTP GET program for the ESP32.

Just to confirm the results, you can check at figure 2 the output returned when accessing the URL directly on a web browser. As can be seen, the answer is the same.

Fake online REST API answer

Figure 2 – Accessing the URL directly on a web browser.

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

6 Responses to ESP32: HTTP GET Requests

  1. Pingback: ESP32: HTTP POST Requests | techtutorialsx

  2. Pingback: 【FF14】 リアルで侍をプレイする刀コントローラを作る(無線デバイス制御編その1 HTTPClient) | スミノアメ

  3. Pingback: ESP32 Arduino: Getting started with WiFi | techtutorialsx

  4. Pingback: ESP32 Arduino: HTTP POST Requests to Bottle application | techtutorialsx

  5. Pingback: ESP32: Getting started with the aREST library | techtutorialsx

  6. Pingback: ESP32 Arduino: HTTPS GET REQUEST | techtutorialsx

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