Language: EN

como-emplear-el-esp8266-como-cliente-http

How to use ESP8266 or ESP32 as an HTTP client

We continue with the tutorials of the ESP8266 and ESP32 seeing how to use the ESP8266 as an HTTP client.

We will refer to the ESP8266, but the same code is compatible for the ESP32, adjusting the name of the libraries. At the end you have the code for both the ESP8266 and the ESP32.

In previous posts we have already seen how to connect the ESP8266 in both STA mode and AP mode, how to set a static IP, and how to use mDNS. Now that we know how to connect our ESP8266, it’s time to start working with it and get the most out of it.

We start by seeing how to use the ESP8266 as a client. Remember that in machine to machine communication, the client is simply the device that initiates the connection. In the next posts, we will delve into its use as a server.

Why use the ESP8266 as a client?

It is very common to find projects in which the ESP8266 acts as a server and another device (a mobile phone, a computer, etc.) acts as a client. So much so, that sometimes in many cases and tutorials the functionality as a client is overlooked.

ESP8266-cliente-servidor

So, in what situations is it useful for the ESP8266 to act as a client? Plenty! Remember that the client is simply the device that initiates the communication. Let’s mention some examples.

A very didactic example (although not particularly realistic) is to obtain a web page to process/parse the content of the web page in search of certain information. Typical examples are, for example, reading the time, or the weather forecast.

In more practical cases, it is, for example, obtaining information provided by a server that facilitates making a call to an endpoint/URL, for example, in CSV, JSON, or XML format.

Another real example is making a request against an endpoint of a certain API (usually a REST API) to execute an action on a remote server (turn on a light, open a door…)

Finally, as another real example, we can initiate a connection to send information to a server for processing (for example, a Raspberry Pi) to store the value in a database, calculate statistics, etc.

In short, we will use it to communicate with and transfer information to another device (including between two ESP8266). As we can see, we should not underestimate the functionality of the ESP8266 as a client.

ESP8266 as a client

As usual, using the ESP8266 as a client is really simple thanks to the ESP8266HTTPClient library and the great work developed by the community.

To initiate the connection as a client, we use the http.begin(…) function, which requires an instance of the HTTPClient object and WiFiClient, and accepts the following overloads.

bool begin(WiFiClient &client, String url);
bool begin(WiFiClient &client, String host, uint16_t port, String uri = "/", bool https = false);

The http.begin(…) method returns true if the connection has been successfully established. Once the connection is initiated, we can make an HTTP request, for example, http.GET();

In the case of the ESP32, the library is called ‘HTTPClient’ instead of ‘ESP8266HTTPClient’.

Example

Let’s see all this together in an example. And, of course, we are going to choose the didactic (although not very useful) example of displaying the content of a web page via serial port. For example, from ’http://www.google.com‘.

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

// Replace with your WiFi data
const char* ssid = "ssid";
const char* password = "password";
String url = "http://www.google.com";

void setup()
{
  Serial.begin(115200);
  delay(10);

  // Connect to WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) 
    delay(500);
}

void loop()
{
  HTTPClient http;
  WiFiClient client;

  if (http.begin(client, url)) //Initiate connection
  {
    Serial.print("[HTTP] GET...\n");
    int httpCode = http.GET();  // Make request

    if (httpCode > 0) {
      Serial.printf("[HTTP] GET... code: %d\n", httpCode);

      if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
        String payload = http.getString();  // Get response
        Serial.println(payload);  // Display response via serial
      }
    }
    else {
      Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
    }

    http.end();
  }
  else {
    Serial.printf("[HTTP} Unable to connect\n");
  }

  delay(30000);
}

If everything went well, we will see a very long text on the serial monitor, which is the content of the web page at www.google.com.

esp8266-cliente-demo

That’s how easy it is! Of course, the ESP8266HTTPClient library has many more aspects to comment on. Next, we will go into a little more detail.

ESP8266HTTPClient in detail

The HTTPClient class is capable of making other types of HTTP requests besides GET. For this, we have the following methods.

int GET();
int POST(String payload);
int PUT(String payload);
int PATCH(String payload);

As we can see, except for GET, they accept a String with the request body. These methods are nothing more than aliases (‘syntactic sugar’) for the more general ‘sendRequest(…)’ method, where ‘type’ indicates the type of request to be made (GET, POST, PUT…

int sendRequest(const char * type, String payload);

We will use the general method, for example, in DELETE requests, as we miss a direct method to execute it, and it is a necessary verb to interact with a REST API.

The request methods return an integer with the response code of the request. Remember that these codes are standard in HTTP and are divided into families:

  • 1xx: Informational
  • 2xx: Success
  • 3xx: Redirection
  • 4xx: Client Error
  • 5xx: Server Error

The library defines aliases for the main types of response codes. There are many types of codes, but some of the most common ones are.

CODEESP8266 AliasMeaning
200HTTP_CODE_OKOK
300HTTP_CODE_MULTIPLE_CHOICESMultiple Choices
301HTTP_CODE_MOVED_PERMANENTLYMoved Permanently
302HTTP_CODE_FOUNDFound
304HTTP_CODE_NOT_MODIFIEDNot Modified
400HTTP_CODE_BAD_REQUESTBad Request
401HTTP_CODE_UNAUTHORIZEDUnauthorized
403HTTP_CODE_FORBIDDENForbidden
404HTTP_CODE_NOT_FOUNDNot Found
410HTTP_CODE_GONEGone
500HTTP_CODE_INTERNAL_SERVER_ERRORInternal Server Error
501HTTP_CODE_NOT_IMPLEMENTEDNot Implemented
503HTTP_CODE_BAD_GATEWAYService Unavailable

It is also possible to add headers to the request with the function

void addHeader(const String& name, const String& value, bool first = false, bool replace = true);

Finally, it is worth mentioning that it is possible to use the http.begin(…) function without using an instance of WiFiClient with the following overloads

bool begin(String url)  __attribute__ ((deprecated));
bool begin(String host, uint16_t port, String uri = "/")  __attribute__ ((deprecated));

Although it is very common to find them in tutorials and projects, note that these functions are deprecated, and do not allow the use of the methods and functionalities provided by the WiFiClient class.

In case anyone is wondering, no, the program generated with these functions is neither smaller nor more efficient. In fact, it is the opposite.

Summarized example

To make the code simpler and more convenient, as usual in this section, we are going to divide the code into files. In addition to our usual ‘config.h’ and ‘ESP8266_Utils.hpp’, we will add the following

The main program is reduced to the following code,

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

String url = "http://www.google.com";

#include "config.h"  // Replace with your network data
#include "Client.hpp"
#include "ESP8266_Utils.hpp"
#include "ESP8266_Utils_Client.hpp"
 
void setup()
{
   Serial.begin(115200);
 
   ConnectWiFi_STA();
}
 
void loop()
{
   ClientRequest();
 
   delay(30000);
}

A ‘ESP8266_Utils_Client.hpp’ file with the following content,

void ClientRequest()
{
   if (http.begin(client, url)) //Initiate connection
   {
      Serial.print("[HTTP] GET...\n");
      int httpCode = http.GET();  // Make request
 
      if (httpCode > 0) {
         Serial.printf("[HTTP] GET... code: %d\n", httpCode);
 
         if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
            String payload = http.getString();   // Get response
            ProcessResponse(payload);
         }
      }
      else {
         Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
      }
 
      http.end();
   }
   else {
      Serial.printf("[HTTP} Unable to connect\n");
   }
 
}

On the other hand, we create a ‘Client.hpp’ file that will contain the functions to execute when obtaining the response. In this example, we will only display the response obtained via Serial, so the code is as follows.

void ProcessResponse(String response)
{
   Serial.println(response);   // Display response via serial
}

That’s the tutorial on how to use the ESP8266 as a client. Of course, there are many more functions and constants in the ESP8266HTTPClient library. If you are curious, check out its code, reading it is very interesting.

In a future post, we will see how to use these functions to consume a REST API and interact with other devices. But that will be later, after we have seen the rest of the more basic aspects of the ESP8266.

For now, in the next post we will start with the ESP8266 acting as a server. We have plenty of fun ahead!

Download the code

All the code from this post is available for download on Github.

github-full

Version for the ESP8266: https://github.com/luisllamasbinaburo/ESP8266-Examples

Version for the ESP32: https://github.com/luisllamasbinaburo/ESP32-Examples