ESP32 WebServer Library – responseHeaderName()

Home / References / ESP32 Library / WebServer Library

Description

The responseHeaderName() method is used to retrieve the name of a response header by its index position. This method returns the header name as a String from the list of HTTP response headers that have been added to the current response using the sendHeader() method. It’s particularly useful for debugging HTTP responses, logging server activity, implementing dynamic header inspection, and iterating through all response headers to validate their presence. The method works in conjunction with responseHeaders() to provide complete access to response header information, enabling developers to inspect, log, or process all headers being sent to clients.


Syntax and Usage

The responseHeaderName() method has a simple syntax:

  • Get header name by index: String headerName = server.responseHeaderName(index) – Returns the name of the response header at the specified index position.

Arguments

  • i (int) – The zero-based index of the response header whose name you want to retrieve. Must be between 0 and responseHeaders()-1.

Return Value

The responseHeaderName() method returns a const String& containing the name of the response header at the specified index. If the index is out of bounds (greater than or equal to the number of response headers), the method returns an empty string. The returned string is a reference to the actual header name stored internally by the WebServer.

This webpage is part of the Comprehensive Guide to the ESP32 Arduino Core Library, accessible on AvantMaker.com.


Example Code

HTTP Response Header Inspector with Header Name Enumeration

This example demonstrates how to use the responseHeaderName() method to inspect and display all response header names. The server shows how to iterate through response headers, retrieve their names, and provide detailed information about each header for debugging and monitoring purposes.

How to use this example: Upload this code to your ESP32 and replace the WiFi credentials. After connecting, access the main page at http://ESP32_IP/ to see the response header inspector. Test different endpoints to see various header configurations: http://ESP32_IP/api/json for JSON responses, http://ESP32_IP/api/secure for security headers, and http://ESP32_IP/api/custom for custom headers. The interface will show both header names and values, demonstrating how responseHeaderName() works alongside other response header methods.

/*
 * Author: Avant Maker
 * Date: June 18, 2025
 * Version: 1.0
 * License: MIT 
 * 
 * Description: 
 * This example demonstrates how to use the responseHeaderName() method to
 * inspect and display all response header names. The server shows how to
 * iterate through response headers, retrieve their names, and provide
 * detailed information about each header for debugging and monitoring purposes.
 *
 * How to use this example:
 * Upload this code to your ESP32 and replace the WiFi credentials.
 * After connecting, access the main page at http://ESP32_IP/ to see the
 * response header inspector. Test different endpoints to see various header
 * configurations: http://ESP32_IP/api/json for JSON responses,
 * http://ESP32_IP/api/secure for security headers, and
 * http://ESP32_IP/api/custom for custom headers. The interface will show
 * both header names and values, demonstrating how responseHeaderName()
 * works alongside other response header methods.
 *
 * 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);

// Statistics for header tracking
struct HeaderInspectionStats {
  unsigned long totalRequests = 0;
  unsigned long totalHeadersInspected = 0;
  String mostCommonHeaderName = "";
  int maxHeadersInSingleResponse = 0;
} stats;

// Function to log and inspect response headers
void inspectResponseHeaders(const String& endpoint) {
  int headerCount = server.responseHeaders();
  stats.totalRequests++;
  stats.totalHeadersInspected += headerCount;
  
  if (headerCount > stats.maxHeadersInSingleResponse) {
    stats.maxHeadersInSingleResponse = headerCount;
  }
  
  Serial.println("=== Response Header Inspection for " + endpoint + " ===");
  Serial.println("Total response headers: " + String(headerCount));
  
  for (int i = 0; i < headerCount; i++) {
    String headerName = server.responseHeaderName(i);
    String headerValue = server.responseHeader(i);
    Serial.println("Header[" + String(i) + "] Name: '" + headerName + "' = '" + headerValue + "'");
  }
  Serial.println("=== End Header Inspection ===");
}

void handleRoot() {
  // Add various custom headers for demonstration
  server.sendHeader("X-Server-Type", "ESP32 Header Inspector");
  server.sendHeader("X-Response-Time", String(millis()));
  server.sendHeader("X-Demo-Version", "1.0");
  server.sendHeader("X-Framework", "Arduino Core");
  
  // Inspect headers before sending response
  inspectResponseHeaders("/");
  
  String html = "<!DOCTYPE html><html><head>";
  html += "<title>AvantMaker ESP32 Response Header Name Inspector</title>";
  html += "<meta name='viewport' content='width=device-width, initial-scale=1'>";
  html += "<style>";
  html += "body{font-family:Arial,sans-serif;margin:20px;background:#f0f8ff;}";
  html += ".container{max-width:1000px;margin:0 auto;background:white;padding:30px;border-radius:12px;box-shadow:0 6px 20px rgba(0,0,0,0.1);}";
  html += ".header-display{background:#f8f9fa;padding:20px;border-radius:8px;margin:20px 0;border-left:4px solid #28a745;}";
  html += ".header-item{background:#e9ecef;margin:8px 0;padding:12px;border-radius:6px;display:flex;justify-content:space-between;}";
  html += ".header-name{font-weight:bold;color:#495057;flex:1;}";
  html += ".header-value{color:#6c757d;flex:2;word-break:break-all;}";
  html += ".stats-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:15px;margin:20px 0;}";
  html += ".stat-card{background:linear-gradient(135deg,#667eea 0%,#764ba2 100%);color:white;padding:20px;border-radius:10px;text-align:center;}";
  html += ".stat-number{font-size:2.2em;font-weight:bold;margin-bottom:8px;}";
  html += ".stat-label{font-size:0.9em;opacity:0.9;}";
  html += ".test-buttons{display:flex;flex-wrap:wrap;gap:12px;margin:20px 0;}";
  html += ".btn{background:#007bff;color:white;padding:12px 20px;border:none;border-radius:6px;text-decoration:none;transition:all 0.3s;}";
  html += ".btn:hover{background:#0056b3;transform:translateY(-2px);}";
  html += ".btn.success{background:#28a745;} .btn.success:hover{background:#1e7e34;}";
  html += ".btn.warning{background:#ffc107;color:#212529;} .btn.warning:hover{background:#e0a800;}";
  html += ".btn.info{background:#17a2b8;} .btn.info:hover{background:#138496;}";
  html += "</style></head><body>";
  
  html += "<div class='container'>";
  html += "<h1>AvantMaker ESP32 Response Header Name Inspector</h1>";
  html += "<p>This tool demonstrates the <code>responseHeaderName()</code> method by showing all response header names and values.</p>";
  
  // Display current response headers
  html += "<div class='header-display'>";
  html += "<h3>Current Response Headers (Total: " + String(server.responseHeaders()) + ")</h3>";
  
  for (int i = 0; i < server.responseHeaders(); i++) {
    String headerName = server.responseHeaderName(i);
    String headerValue = server.responseHeader(i);
    html += "<div class='header-item'>";
    html += "<div class='header-name'>[" + String(i) + "] " + headerName + ":</div>";
    html += "<div class='header-value'>" + headerValue + "</div>";
    html += "</div>";
  }
  html += "</div>";
  
  // Display statistics
  html += "<div class='stats-grid'>";
  html += "<div class='stat-card'><div class='stat-number'>" + String(stats.totalRequests) + "</div><div class='stat-label'>Total Requests</div></div>";
  html += "<div class='stat-card'><div class='stat-number'>" + String(stats.totalHeadersInspected) + "</div><div class='stat-label'>Headers Inspected</div></div>";
  html += "<div class='stat-card'><div class='stat-number'>" + String(stats.maxHeadersInSingleResponse) + "</div><div class='stat-label'>Max Headers/Response</div></div>";
  
  float avgHeaders = (stats.totalRequests > 0) ? (float)stats.totalHeadersInspected / stats.totalRequests : 0;
  html += "<div class='stat-card'><div class='stat-number'>" + String(avgHeaders, 1) + "</div><div class='stat-label'>Avg Headers/Response</div></div>";
  html += "</div>";
  
  // Test buttons
  html += "<h3>🧪 Test Different Header Configurations</h3>";
  html += "<div class='test-buttons'>";
  html += "<a href='/api/json' class='btn success'>JSON API (Content-Type)</a>";
  html += "<a href='/api/secure' class='btn warning'>Security Headers</a>";
  html += "<a href='/api/custom' class='btn info'>Custom Headers</a>";
  html += "<a href='/api/minimal' class='btn'>Minimal Headers</a>";
  html += "<a href='/stats/reset' class='btn'>Reset Stats</a>";
  html += "</div>";
  
  // Instructions
  html += "<h3>📋 How to Use</h3>";
  html += "<ul>";
  html += "<li>Click the test buttons above to see different header configurations</li>";
  html += "<li>Each response will show the header names retrieved by <code>responseHeaderName()</code></li>";
  html += "<li>Check the browser developer tools (F12 → Network tab) to verify header transmission</li>";
  html += "<li>Monitor the Serial output for detailed header inspection logs</li>";
  html += "</ul>";
  
  html += "<h3>📊 System Information</h3>";
  html += "<p>Free Heap: " + String(ESP.getFreeHeap()) + " bytes | ";
  html += "Uptime: " + String(millis()/1000) + "s | ";
  html += "WiFi Signal: " + String(WiFi.RSSI()) + " dBm</p>";
  
  html += "</div></body></html>";
  
  server.send(200, "text/html", html);
}

void handleJSONAPI() {
  // Add JSON-specific headers
  server.sendHeader("X-API-Type", "JSON");
  server.sendHeader("X-Response-Format", "application/json");
  
  inspectResponseHeaders("/api/json");
  
  String json = "{";
  json += "\"message\":\"JSON API Response\",";
  json += "\"responseHeaders\":" + String(server.responseHeaders()) + ",";
  json += "\"headerNames\":[";
  
  for (int i = 0; i < server.responseHeaders(); i++) {
    if (i > 0) json += ",";
    json += "\"" + server.responseHeaderName(i) + "\"";
  }
  
  json += "],\"timestamp\":" + String(millis()) + "}";
  
  server.send(200, "application/json", json);
}

void handleSecureAPI() {
  // Add comprehensive security headers
  server.sendHeader("X-Content-Type-Options", "nosniff");
  server.sendHeader("X-Frame-Options", "DENY");
  server.sendHeader("X-XSS-Protection", "1; mode=block");
  server.sendHeader("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
  server.sendHeader("Content-Security-Policy", "default-src 'self'");
  server.sendHeader("Referrer-Policy", "strict-origin-when-cross-origin");
  
  inspectResponseHeaders("/api/secure");
  
  String response = "Secure API Response\n\n";
  response += "Security headers added: " + String(server.responseHeaders()) + "\n\n";
  response += "Header names:\n";
  
  for (int i = 0; i < server.responseHeaders(); i++) {
    response += String(i+1) + ". " + server.responseHeaderName(i) + "\n";
  }
  
  server.send(200, "text/plain", response);
}

void handleCustomAPI() {
  // Add various custom headers
  server.sendHeader("X-Custom-Header-1", "Value1");
  server.sendHeader("X-Custom-Header-2", "Value2");
  server.sendHeader("X-Application-Name", "ESP32 Header Inspector");
  server.sendHeader("X-Developer", "Avant Maker");
  server.sendHeader("X-Build-Date", "June 2025");
  server.sendHeader("X-Feature-Flags", "header-inspection,logging,stats");
  
  inspectResponseHeaders("/api/custom");
  
  String response = "Custom Headers API Response\n\n";
  response += "Total headers: " + String(server.responseHeaders()) + "\n\n";
  response += "Complete header list:\n";
  
  for (int i = 0; i < server.responseHeaders(); i++) {
    String name = server.responseHeaderName(i);
    String value = server.responseHeader(i);
    response += "[" + String(i) + "] " + name + " = " + value + "\n";
  }
  
  server.send(200, "text/plain", response);
}

void handleMinimalAPI() {
  // No custom headers - just default ones
  inspectResponseHeaders("/api/minimal");
  
  String response = "Minimal API Response\n\n";
  response += "Headers (minimal set): " + String(server.responseHeaders()) + "\n\n";
  
  for (int i = 0; i < server.responseHeaders(); i++) {
    response += server.responseHeaderName(i) + "\n";
  }
  
  server.send(200, "text/plain", response);
}

void handleResetStats() {
  stats.totalRequests = 0;
  stats.totalHeadersInspected = 0;
  stats.mostCommonHeaderName = "";
  stats.maxHeadersInSingleResponse = 0;
  
  server.send(200, "text/plain", "Statistics reset!\n\nGo back to: http://" + WiFi.localIP().toString());
  Serial.println("Header inspection statistics reset");
}

void setup() {
  Serial.begin(115200);
  Serial.println("Starting AvantMaker ESP32 Response Header Name Inspector...");
  
  // Connect to WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  
  Serial.println("WiFi connected!");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  
  // Set up route handlers
  server.on("/", handleRoot);
  server.on("/api/json", handleJSONAPI);
  server.on("/api/secure", handleSecureAPI);
  server.on("/api/custom", handleCustomAPI);
  server.on("/api/minimal", handleMinimalAPI);
  server.on("/stats/reset", handleResetStats);
  
  // Start server
  server.begin();
  Serial.println("HTTP server started");
  Serial.println("Header name inspector available at: http://" + WiFi.localIP().toString());
  Serial.println("Monitor Serial output for detailed header inspection logs");
}

void loop() {
  server.handleClient();
  
  // Optional: Print periodic statistics
  static unsigned long lastPrint = 0;
  if (millis() - lastPrint > 60000) { // Every 60 seconds
    lastPrint = millis();
    if (stats.totalRequests > 0) {
      Serial.println("📊 Header Inspection Stats:");
      Serial.println("  Requests: " + String(stats.totalRequests));
      Serial.println("  Headers inspected: " + String(stats.totalHeadersInspected));
      Serial.println("  Max headers in single response: " + String(stats.maxHeadersInSingleResponse));
      Serial.println("  Average headers per response: " + String((float)stats.totalHeadersInspected / stats.totalRequests, 2));
    }
  }
}

For more ESP32 development resources and tutorials, visit the All About ESP32 Resources Hub on  AvantMaker.com

error: Content is protected !!