ESP32 HTTPClient Library – collectHeaders

Home / References / ESP32 Library / HTTPClient

Description

The collectHeaders method in the ESP32 HTTPClient Library allows you to specify which HTTP response headers you want to capture from a server’s response. By calling this method before sending an HTTP request, you can collect specific header values, which can then be accessed later using the header method. This is particularly useful for makers and enthusiasts looking to extract metadata like rate limits, content types, or custom server information from HTTP responses, enhancing the functionality of your ESP32-based innovations.


Syntax and Usage

The collectHeaders method has a single way of being used, requiring both the header keys and their count as arguments. Here’s how to implement it:

void collectHeaders(const char* headerKeys[], const size_t headerKeysCount);
  • With Arguments: Use this method by passing an array of header names and the number of headers you want to collect. This prepares the HTTPClient object to store the specified headers from the server’s response for later retrieval.

Note: Without calling collectHeaders first, the header(), headerName(), and hasHeader() methods of the ESP32 HTTPClient library will not work effectively.

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 collectHeaders method requires two arguments to function correctly. Here’s a breakdown:

  • headerKeys: An array of const char* pointers, where each element is the name of an HTTP header you want to collect (e.g., "Content-Type""x-ratelimit-remaining"). This tells the library which headers to watch for in the response.
  • headerKeysCount: A size_t value representing the number of headers in the headerKeys array. This ensures the library knows how many headers to process.

Return Value

The collectHeaders method does not return a value (it has a void return type). Its purpose is to configure the HTTPClient object to capture the specified headers during the HTTP request processing. After the request is made, you can retrieve the collected header values using the header method.


Example Codes

Below is an example demonstrating how to use the collectHeaders method with arguments. This example connects to www.httpbin.org, a handy testing service, to retrieve specific response headers.

Example: Collecting and Displaying Specific Headers

This code sets up an ESP32 to connect to Wi-Fi, make an HTTP GET request to www.httpbin.org/get, and collect headers. After the request, it prints the collected header values to the Serial Monitor. Use this as a starting point to experiment with headers in your projects!

/*
 * Author: Avant Maker
 * Date: February 24, 2025
 * Version: 1.0
 * Description: This example code demostrates how to use
 * ESP32 HTTPClient Library's collectHeaders to collect 
 * two custom headers: Content-Type and Server.
 *
 * 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 Wi-Fi!");
}

void loop() {
    if (WiFi.status() == WL_CONNECTED) {
        HTTPClient http;

        // Define the headers to collect
        const char* headerKeys[] = {"Content-Type", "Server"};
        const size_t headerKeysCount = 2;

        // Configure HTTPClient to collect the specified headers
        http.collectHeaders(headerKeys, headerKeysCount);

        // Start the HTTP request
        http.begin("http://www.httpbin.org/get");
        int httpCode = http.GET();

        if (httpCode > 0) {
            // Request successful, print the collected headers
            Serial.printf("HTTP Response Code: %d\n", httpCode);
            for (size_t i = 0; i < headerKeysCount; i++) {
                String headerValue = http.header(headerKeys[i]);
                Serial.printf("Header %s: %s\n", headerKeys[i], headerValue.c_str());
            }
        } else {
            Serial.println("Error on HTTP request");
        }

        http.end(); // Free resources
    }

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