ESP32 WiFiClientSecure Library – read

Home / References / ESP32 Library / WiFiClientSecure

Description

The read method in the WiFiClientSecure library is used to retrieve data from a secure network connection established with an ESP32. This method is essential for reading incoming data from a server over a TLS/SSL-encrypted connection, making it a key tool for secure communication projects. Whether you’re fetching data from a web server or handling responses in IoT applications, read enables you to process the received bytes efficiently.


Syntax and Usage

The read method can be used in two different ways depending on whether you want to read a single byte or multiple bytes into a buffer. Below are the syntax options:

Reading a single byte:

client.read()

This usage reads one byte of data from the secure connection and returns it as an integer. It’s ideal for processing data character by character.

Reading multiple bytes into a buffer:

client.read(uint8_t *buf, size_t size)

This usage reads a specified number of bytes into a provided buffer, returning the number of bytes actually read. It’s useful for handling larger data chunks efficiently.

For practical applications and examples of this method, please consult the “Example Code” section on this page. This section provides comprehensive guidance to help you better understand and apply the method effectively.


Argument(s)

The read method can be used with or without arguments, depending on the syntax chosen:

  • No arguments (for single byte): When called without arguments, read() does not require any parameters and simply reads the next available byte.
  • With arguments (for buffer):
    • uint8_t *buf: A pointer to an array of unsigned 8-bit integers where the read data will be stored.
    • size_t size: The maximum number of bytes to read into the buffer. This specifies the buffer’s capacity.

Return Value

The return value of the read method depends on how it is used:

  • For read() (no arguments): Returns an int representing the next byte of data (0 to 255). If no data is available or the connection is closed, it returns -1.
  • For read(uint8_t *buf, size_t size): Returns a size_t indicating the number of bytes successfully read into the buffer. Returns 0 if no data is available or an error occurs.

Example Codes

Below are example codes demonstrating both ways of using the read method. Each example includes an explanation to guide you in applying it to your projects.

Example 1: Reading a Single Byte

This example connects to a secure server and reads data one byte at a time, printing each character to the Serial Monitor. It’s useful for simple debugging or processing small responses.

ATTENTION: The Root CA certificate has an expiration date. If the code fails to execute, it may be due to the Root CA certificate has expired. Try obtaining the latest Root CA certificate and replacing the expired one in this code. For detailed instructions on acquiring a website’s Root CA certificate, check out the link below:
How to Acquire the Root CA Certificate

/*
 * Author: Avant Maker
 * Date: February 24, 2025
 * Version: 1.0
 *
 * Description: This example demostrate how to use 
 * ESP32 WiFiClientSecure Libary's 
 * read method to read server response byte-by-byte then
 * print it to the Serial Monitor.
 * 
 * ATTENTION: The Root CA certificate has an expiration date. 
 * If the code fails to execute, the Root CA
 * certificate may have expired. If this code fails to execute,
 * it may be due to an expired Root CA certificate.
 * Try obtaining the latest Root CA certificate and
 * replacing the expired one in the code.
 * For detailed instructions on acquiring a website's
 * Root CA certificate, check out the link below:
 *
 * https://avantmaker.com/references/esp32-arduino-core-index/esp32-wificlientsecure-library/how-to-acquire-the-root-ca-certificate/
 *
 * License: MIT 
 * 
 * Code Source: This example code is sourced from the Comprehensive 
 * Guide to the ESP32 Arduino Core Library, accessible on 
 * AvantMaker.com. For additional code examples and in-depth 
 * documentation related to the ESP32 Arduino Core Library, 
 * please visit:
 *
 * https://avantmaker.com/references/esp32-arduino-core-index/
 *
 * AvantMaker.com, your premier destination for all things 
 * DIY, AI, IoT, Smart Home, and STEM projects. We are dedicated 
 * to empowering makers, learners, and enthusiasts with the resources
 * they need to bring their innovative ideas to life.
 */

#include <WiFi.h>
#include <NetworkClientSecure.h>

const char* ssid = "your-SSID";          // Replace with your Wi-Fi SSID
const char* password = "your-PASSWORD"; // Replace with your Wi-Fi password
const char* host = "www.httpbin.org";
const int port = 443;

// Root CA certificate for www.httpbin.org (update with your server's CA if different)
const char* rootCACert = R"literal(
-----BEGIN CERTIFICATE-----
MIIEXjCCA0agAwIBAgITB3MSSkvL1E7HtTvq8ZSELToPoTANBgkqhkiG9w0BAQsF
ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6
b24gUm9vdCBDQSAxMB4XDTIyMDgyMzIyMjUzMFoXDTMwMDgyMzIyMjUzMFowPDEL
MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEcMBoGA1UEAxMTQW1hem9uIFJT
QSAyMDQ4IE0wMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALtDGMZa
qHneKei1by6+pUPPLlj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tQOcNRWz5qCQdD
slI2yayq0n2TXoHyNCLEH8rpsJRVILFsg0jc7BaFrMnF462+ajSehgj12IidNeRN
4zl+EoNaWdpnWndvSpAEkq2P
-----END CERTIFICATE-----
)literal";

// Optional: Add client certificate and key for mutual TLS if needed
// const char* clientCertKey = "";
// const char* clientCert = "";

NetworkClientSecure secureClient;

void setup() {
    Serial.begin(115200);
    
    // Connect WiFi
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println("Connected to WiFi");

    // Set the Root CA Cert
    secureClient.setCACert(rootCACert);

    // Establish secure connection to server
    if (secureClient.connect(host, port)) {
        Serial.println("Connected to server");

        // Create the POST data
        String postData = "AvantMaker=HelloFromESP32";

        // Send the POST request
        secureClient.print("POST /post HTTP/1.1\r\n");
        secureClient.print("Host: www.httpbin.org\r\n");
        secureClient.print("Content-Type: application/x-www-form-urlencoded\r\n");
        secureClient.print("Content-Length: ");
        secureClient.print(postData.length());
        secureClient.print("\r\nConnection: close\r\n\r\n");
        secureClient.print(postData);

        // Wait for and display server response
        delay(1000); // Give server time to respond
        Serial.println("Server response:");
        while (secureClient.available()) {
            char c = secureClient.read();
            Serial.write(c);
        }

    } else {
        Serial.println("Failed to connect to server! Check the code description for solution.");
        return;
    }     
}

void loop() {

}

Example 2: Reading Multiple Bytes into a Buffer

This example reads data in chunks into a buffer, which is more efficient for handling larger responses. It connects to a secure server and prints the received data as a string.

ATTENTION: The Root CA certificate has an expiration date. If the code fails to execute, it may be due to the Root CA certificate has expired. Try obtaining the latest Root CA certificate and replacing the expired one in this code. For detailed instructions on acquiring a website’s Root CA certificate, check out the link below:
How to Acquire the Root CA Certificate

/*
 * Author: Avant Maker
 * Date: February 24, 2025
 * Version: 1.0
 *
 * Description: This example demostrate how to use 
 * ESP32 WiFiClientSecure Libary's 
 * read method to read server response into a Buffer
 * and display it in Serial Monitor.
 * 
 * ATTENTION: The Root CA certificate has an expiration date. 
 * If the code fails to execute, it may be due to the Root CA
 * certificate has expired. Try obtaining the latest 
 * Root CA certificate and replacing the expired one in this code.
 * For detailed instructions on acquiring a website's
 * Root CA certificate, check out the link below:
 *
 * https://avantmaker.com/references/esp32-arduino-core-index/esp32-wificlientsecure-library/how-to-acquire-the-root-ca-certificate/
 *
 * License: MIT 
 * 
 * Code Source: This example code is sourced from the Comprehensive 
 * Guide to the ESP32 Arduino Core Library, accessible on 
 * AvantMaker.com. For additional code examples and in-depth 
 * documentation related to the ESP32 Arduino Core Library, 
 * please visit:
 *
 * https://avantmaker.com/references/esp32-arduino-core-index/
 *
 * AvantMaker.com, your premier destination for all things 
 * DIY, AI, IoT, Smart Home, and STEM projects. We are dedicated 
 * to empowering makers, learners, and enthusiasts with the resources
 * they need to bring their innovative ideas to life.
 */

#include <WiFi.h>
#include <NetworkClientSecure.h>

const char* ssid = "your-SSID";          // Replace with your Wi-Fi SSID
const char* password = "your-PASSWORD"; // Replace with your Wi-Fi password

const char* host = "www.httpbin.org";
const int port = 443;

// Root CA certificate for www.httpbin.org (update with your server's CA if different)
const char* rootCACert = R"literal(
-----BEGIN CERTIFICATE-----
MIIEXjCCA0agAwIBAgITB3MSSkvL1E7HtTvq8ZSELToPoTANBgkqhkiG9w0BAQsF
ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6
b24gUm9vdCBDQSAxMB4XDTIyMDgyMzIyMjUzMFoXDTMwMDgyMzIyMjUzMFowPDEL
MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEcMBoGA1UEAxMTQW1hem9uIFJT
QSAyMDQ4IE0wMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALtDGMZa
qHneKei1by6+pUPPLljTB143Si6VpEWPc6mSkFhZb/6qrkZyoHlQLbDYnI2D7hD0
sdzEqfnuAjIsuXQLG3A8TvX6V3oFNBFVe8NlLJHvBseKY88saLwufxkZVwk74g4n
WlNMXzla9Y5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// Optional: Add client certificate and key for mutual TLS if needed
// const char* clientCertKey = "";
// const char* clientCert = "";

NetworkClientSecure secureClient;

void setup() {
    Serial.begin(115200);
    
    // Connect WiFi
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println("Connected to WiFi");

    // Set the Root CA Cert
    secureClient.setCACert(rootCACert);

    // Establish secure connection to server
    if (secureClient.connect(host, port)) {
        Serial.println("Connected to server");

        // Create the POST data
        String postData = "AvantMaker=HelloFromESP32";

        // Send the POST request
        secureClient.print("POST /post HTTP/1.1\r\n");
        secureClient.print("Host: www.httpbin.org\r\n");
        secureClient.print("Content-Type: application/x-www-form-urlencoded\r\n");
        secureClient.print("Content-Length: ");
        secureClient.print(postData.length());
        secureClient.print("\r\nConnection: close\r\n\r\n");
        secureClient.print(postData);

    } else {
        Serial.println("Failed to connect to server! Check the code description for solution.");
        return;
    }     
}

void loop() {
    while (secureClient.available()) {
        // Divide the output with  buffer
        Serial.println("");
        Serial.println("==================");
        uint8_t buffer[64];              // Buffer to store data
        int bytesRead = secureClient.read(buffer, 64); // Read up to 64 bytes
        if (bytesRead > 0) {
            Serial.write(buffer, bytesRead); // Print the buffer content
        }
    }
    if (!secureClient.connected()) {
        secureClient.stop();
        while (true); // Stop after disconnect
    }
}

ESP32 Library Index

ESP32 Arduino Core Library


FAQ

Ready to experiment and explore more about ESP32? Visit our website’s All About ESP32 Resources Hub, packed with tutorials, guides, and tools to inspire your maker journey. Experiment, explore, and elevate your skills with everything you need to master this powerful microcontroller platform!

error: Content is protected !!