ESP32 HTTPClient Library – getStreamPtr

Home / References / ESP32 Library / HTTPClient

Description

The getStreamPtr method is part of the ESP32 HTTPClient Library, designed to provide direct access to the underlying TCP stream of an HTTP connection. This method returns a pointer to the NetworkClient object, allowing you to read raw data from the server response efficiently. It’s especially useful for handling large payloads or streaming data without loading everything into memory at once, empowering makers to build responsive and memory-efficient projects.


Syntax and Usage

The getStreamPtr method is straightforward to use and has a single way of invocation. Below is the syntax along with a code snippet to illustrate its usage:

NetworkClient* stream = http.getStreamPtr();
  • Basic Usage (No Arguments): This method is called on an HTTPClient object after initiating an HTTP request (e.g., via GET or POST). It provides a pointer to the NetworkClient stream if the connection is active, enabling direct reading of the response data.

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)

This method does not require any arguments. It simply returns a pointer to the existing stream associated with the HTTP connection, making it easy to integrate into your ESP32 projects without additional parameters.


Return Value

The getStreamPtr method returns a pointer to a NetworkClient object (NetworkClient*) representing the TCP stream of the HTTP connection. If the connection is active, this pointer allows you to read the server response directly. If no connection exists (e.g., before calling begin() or after end()), it returns nullptr, indicating that no stream is available.


Example Codes

Below is an example demonstrating the use of getStreamPtr in a practical scenario. This example connects to www.httpbin.org to fetch data and reads it directly from the stream.

Example: Streaming Data from an HTTP GET Request

This code demonstrates how to use the ESP32 HTTPClient library’s getStreamPtr() method to retrieve a pointer to the underlying stream of an HTTP response. It sends a GET request to http://www.httpbin.org/get and reads the response data in chunks using the stream pointer, which is useful for handling large or continuous data efficiently.

To use this code, replace “your_SSID” and “your_PASSWORD” with your WiFi credentials. Upload the code to your ESP32 and open the Serial Monitor to see the streamed response. The code reads and prints the data in small chunks, showing how getStreamPtr() can be used to manage response data effectively.

/*
 * Author: Avant Maker
 * Date: February 24, 2025
 * Version: 1.0
 * Description: This example code demonstrates how to 
 * use the ESP32 HTTPClient Library's getStreamPt to 
 * read HTTP response data in chunks.
 *
 * 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 <HTTPClient.h>

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

void setup() {
    Serial.begin(115200);
    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println("\nConnected to WiFi");
}

void loop() {
    HTTPClient http;

    Serial.println("[HTTP] Starting connection...");
    http.begin("http://www.httpbin.org/get");

    Serial.println("[HTTP] Sending GET request...");
    int httpCode = http.GET();

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

        if (httpCode == HTTP_CODE_OK) {
            // Get the stream pointer
            NetworkClient* stream = http.getStreamPtr();

            // Check if stream is available
            if (stream != nullptr) {
                // Buffer to read data
                uint8_t buffer[128] = {0};
                int len = http.getSize(); // -1 if Content-Length not provided

                Serial.println("[HTTP] Reading stream...");
                while (http.connected() && (len > 0 || len == -1)) {
                    size_t size = stream->available();
                    if (size) {
                        int bytesRead = stream->readBytes(buffer, min(sizeof(buffer), size));
                        Serial.write(buffer, bytesRead);

                        if (len > 0) {
                            len -= bytesRead;
                        }
                    }
                    delay(1); // Small delay to avoid overwhelming the loop
                }
                Serial.println("\n[HTTP] Stream reading complete");
            } else {
                Serial.println("[HTTP] No stream available");
            }
        }
    } else {
        Serial.printf("[HTTP] GET failed, error: %s\n", http.errorToString(httpCode).c_str());
    }

    http.end();
    delay(5000); // Wait before next request
}
error: Content is protected !!