ESP32 WebServer Library -collectHeaders()

Home / References / ESP32 Library / WebServer Library

Description

The collectHeaders() method is used to specify which HTTP request headers should be collected and made available for processing when a client sends a request to the ESP32 WebServer. By default, the WebServer only collects a limited set of headers for performance reasons. This method allows you to explicitly define which additional headers you want to capture and access in your request handlers. The method works by setting up a list of header names that the server should parse and store from incoming HTTP requests, making them accessible through the header() method.


Syntax and Usage

The collectHeaders() method can be used in two different ways:

  • With specific header names: 
    server.collectHeaders(headerKeys, headerKeysCount)
    Collects only the specified headers for better performance when you know exactly which headers you need.
  • Collect all headers: 
    server.collectAllHeaders() 
    Collects all incoming request headers, which is useful for debugging or when you need access to any header that might be sent.

Arguments

  • headerKeys[] – An array of const char* containing the names of the headers you want to collect. These should be the exact header names as they appear in HTTP requests (e.g., “Content-Type”, “Authorization”, “User-Agent”).
  • headerKeysCount – A size_t value representing the number of header names in the headerKeys array. This tells the method how many headers to expect in the array.

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.


Return Value

The collectHeaders() method does not return any value (void return type). The method configures the WebServer internally to collect the specified headers, which can then be accessed using the header() method during request processing.


Example Codes

Example 1: Collecting Specific Headers

This example demonstrates how to collect specific headers that your application needs. This is the most efficient approach when you know exactly which headers are required.

How to use this example: Upload this code to your ESP32, replace “your_wifi_ssid” and “your_wifi_password” with your actual WiFi credentials. After connecting, open a web browser and navigate to the ESP32’s IP address (displayed in Serial Monitor). The server will display the User-Agent, Content-Type, and Authorization headers from your browser request. You can test different headers by using browser developer tools or curl commands like: curl -H "Authorization: Bearer test123" http://ESP32_IP

/*
 * Author: Avant Maker
 * Date: June 16, 2025
 * Version: 1.0
 * License: MIT 
 * 
 * Description: 
 * This example demonstrates how to collect specific headers that
 * your application needs. This is the most efficient approach when
 * you know exactly which headers are required.
 *
 * 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/home/all-about-esp32-arduino-core-library/
 *
 * 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 nnovative ideas to life.
 */
#include <WiFi.h>
#include <WebServer.h>

const char* ssid = "your_wifi_ssid";
const char* password = "your_wifi_password";

WebServer server(80);

// Define the headers we want to collect
const char* headerKeys[] = {"User-Agent", "Content-Type", "Authorization"};
const size_t headerKeysCount = sizeof(headerKeys) / sizeof(headerKeys[0]);

void handleRoot() {
  String message = "AvantMakeer ESP32 Web Server\n\n";
  
  // Access collected headers
  if (server.hasHeader("User-Agent")) {
    message += "User-Agent: " + server.header("User-Agent") + "\n";
  }
  
  if (server.hasHeader("Content-Type")) {
    message += "Content-Type: " + server.header("Content-Type") + "\n";
  }
  
  if (server.hasHeader("Authorization")) {
    message += "Authorization: " + server.header("Authorization") + "\n";
  }
  
  server.send(200, "text/plain", message);
}

void setup() {
  Serial.begin(115200);
  
  // Connect to WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  
  // Configure server to collect specific headers
  server.collectHeaders(headerKeys, headerKeysCount);
  
  // Set up route handlers
  server.on("/", handleRoot);
  
  // Start server
  server.begin();
  Serial.println("HTTP server started");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  server.handleClient();
}

Example 2: Conditional Header Collection

This example demonstrates a more advanced scenario where different headers are collected based on the application’s requirements, showing how to dynamically configure header collection.

How to use this example: This creates an API server with authentication. Test the /api endpoint with: curl -H "X-API-Key: your_secret_api_key" http://ESP32_IP/api for successful authentication, or without the header to see the error response. For file uploads, test the /upload endpoint with: curl -X POST -H "Content-Type: application/json" -d "test data" http://ESP32_IP/upload. The server will validate the API key and display information about the uploaded content including content type and length.

/*
 * Author: Avant Maker
 * Date: June 16, 2025
 * Version: 1.0
 * License: MIT 
 * 
 * Description: 
 * This example demonstrates a more advanced scenario where different
 * headers are collected based on the application's requirements,
 * showing how to dynamically configure header collection.
 *
 * 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/home/all-about-esp32-arduino-core-library/
 *
 * 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 nnovative ideas to life.
 */

#include <WiFi.h>
#include <WebServer.h>

const char* ssid = "your_wifi_ssid";
const char* password = "your_wifi_password";

WebServer server(80);

void handleAPI() {
  String response = "{";
  
  // Check for API key in headers
  if (server.hasHeader("X-API-Key")) {
    String apiKey = server.header("X-API-Key");
    if (apiKey == "your_secret_api_key") {
      response += "\"status\":\"success\",";
      response += "\"message\":\"API access granted\"";
    } else {
      response += "\"status\":\"error\",";
      response += "\"message\":\"Invalid API key\"";
    }
  } else {
    response += "\"status\":\"error\",";
    response += "\"message\":\"API key required\"";
  }
  
  // Add client information if available
  if (server.hasHeader("User-Agent")) {
    response += ",\"client\":\"" + server.header("User-Agent") + "\"";
  }
  
  response += "}";
  
  server.send(200, "application/json", response);
}

void handleUpload() {
  if (server.method() == HTTP_POST) {
    String contentType = server.hasHeader("Content-Type") ? 
                        server.header("Content-Type") : "unknown";
    
    String message = "Upload received\n";
    message += "Content-Type: " + contentType + "\n";
    message += "Content-Length: " + String(server.clientContentLength()) + "\n";
    
    server.send(200, "text/plain", message);
  } else {
    server.send(405, "text/plain", "Method Not Allowed");
  }
}

void setup() {
  Serial.begin(115200);
  
  // Connect to WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  
  // Collect headers needed for API and upload functionality
  const char* apiHeaders[] = {"X-API-Key", "User-Agent", "Content-Type"};
  const size_t apiHeaderCount = sizeof(apiHeaders) / sizeof(apiHeaders[0]);
  
  server.collectHeaders(apiHeaders, apiHeaderCount);
  
  // Set up route handlers
  server.on("/api", HTTP_GET, handleAPI);
  server.on("/upload", HTTP_POST, handleUpload);
  
  // Start server
  server.begin();
  Serial.println("HTTP server started");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  server.handleClient();
}
error: Content is protected !!