ESP32 HTTPClient Library – writeToStream

Home / References / ESP32 Library / HTTPClient

Description

The writeToStream method in the ESP32 HTTPClient Library is a powerful tool for retrieving and processing HTTP response data. It allows you to write the entire message body (payload) of an HTTP response directly to a specified Stream object, such as a Serial monitor or a file. This method is particularly useful when you need to handle large responses efficiently without loading the entire payload into memory at once, making it ideal for memory-constrained ESP32 projects.


Syntax and Usage

The writeToStream method has a single, straightforward usage pattern. Below is the syntax and how to incorporate it into your code:

int HTTPClient::writeToStream(Stream* stream)
  • Basic Usage with a Stream: This method writes the HTTP response payload to a provided Stream object. You typically use it after initiating an HTTP request (e.g., via GET() or POST()) and handling the response headers. It’s designed to work with any Stream-compatible object, such as Serial or a File object from a filesystem.

There are no variations in usage (e.g., with or without arguments beyond the required Stream pointer), as this method is specifically designed to transfer the response body to a single Stream target.

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)

  • stream (Stream*): A pointer to a Stream object where the HTTP response payload will be written. This can be a Serial stream (e.g., &Serial), a File object, or any other class derived from the Arduino Stream class. The method reads the response data from the server and writes it to this stream incrementally.

Return Value

The writeToStream method returns an integer representing the number of bytes successfully written to the provided Stream. If an error occurs, it returns a negative value corresponding to an error code defined in the HTTPClient Library (e.g., HTTPC_ERROR_STREAM_WRITE(-10) for stream write errors or HTTPC_ERROR_TOO_LESS_RAM(-8) for memory issues). A positive value indicates the total bytes transferred, while a negative value helps you diagnose issues during the transfer process.


Example Codes

Below is an example demonstrating how to use the writeToStream method. This example aligns with the single usage pattern described in Section 2 and connects to www.httpbin.org for a practical demonstration.

Example: Writing an HTTP Response to Serial

This example shows how to use writeToStream to send the payload of an HTTP GET request to the Serial monitor. It connects to www.httpbin.org/get, which returns a simple JSON response, and prints it to Serial for debugging or display purposes.

Replace your-SSID and your-PASSWORD with your WiFi credentials. Upload the code to your ESP32, open the Serial Monitor at 115200 baud, and watch as the JSON response from www.httpbin.org/get is printed. This example is perfect for learning how to handle HTTP responses and debug your projects efficiently.

/*
 * Author: Avant Maker
 * Date: February 24, 2025
 * Version: 1.0
 * Description: This example code demonstrates how to 
 * use the ESP32 HTTPClient Library's writeToStream to
 * send the payload of an HTTP GET request to the Serial monitor. 
 *
 * 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() {
    if (WiFi.status() == WL_CONNECTED) {
        HTTPClient http;

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

        int httpCode = http.GET(); // Send the GET request
        if (httpCode > 0) {
            Serial.printf("[HTTP] GET successful, code: %d\n", httpCode);
            if (httpCode == HTTP_CODE_OK) {
                int bytesWritten = http.writeToStream(&Serial); // Write response to Serial
                if (bytesWritten > 0) {
                    Serial.printf("\n[HTTP] Wrote %d bytes to Serial\n", bytesWritten);
                } else {
                    Serial.printf("[HTTP] Error writing to stream: %d\n", bytesWritten);
                }
            }
        } else {
            Serial.printf("[HTTP] GET failed, error: %s\n", http.errorToString(httpCode).c_str());
        }

        http.end(); // Close the connection
    }

    delay(10000); // Wait 10 seconds before the next request
}
error: Content is protected !!