Home / References / ESP32 Library / HTTPClient
Description
The addHeader
method in the ESP32 HTTPClient Library allows you to append custom HTTP headers to your outgoing requests. Headers are essential for defining the behavior of your HTTP communication, such as specifying content types, authentication tokens, or custom metadata. This method is particularly useful when interacting with APIs or servers that require specific header information to process your requests correctly.
Syntax and Usage
The addHeader
method can be used in different ways depending on your needs. Below are the available syntax options, each with a short description:
- Basic Usage with Name and Value: Adds a header with a specified name and value. Ideal for simple header additions like content type or authorization.
- Advanced Usage with First and Replace Flags: Provides additional control by allowing you to specify whether this header should be the first in the list or replace an existing header with the same name.
For more detailed information and examples of the syntax and usage 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 addHeader
method accepts the following arguments:
- name (String): The name of the HTTP header (e.g., “Content-Type”, “Authorization”). This is case-insensitive and must not be one of the headers managed internally by the library (like “Connection” or “Host”).
- value (String): The value associated with the header name (e.g., “application/json”, “Bearer token123”).
- first (bool, optional): If
true
, the header is added at the beginning of the header list. Defaults tofalse
, appending it to the end. - replace (bool, optional): If
true
, replaces an existing header with the same name. Defaults tofalse
, allowing multiple headers with the same name to coexist.
Return Value
The addHeader
method does not return a value (void). It modifies the internal header list of the HTTPClient object, which is then sent with the subsequent HTTP request (e.g., via http.POST()
or http.GET()
). If the header is invalid or restricted (e.g., attempting to set “Connection”), it is silently ignored by the library.
Example Codes
Below are example codes demonstrating the different ways to use the addHeader
method. Each example connects to www.httpbin.org
, a handy testing service that echoes back request details, making it perfect for learning HTTP interactions.
Example 1: Basic Usage with Name and Value
This example shows how to add a simple “Content-Type” header and a custom “Code-Source” header with the value “AvantMaker” to a POST request. It sends a JSON payload to httpbin.org and prints the server’s response.
Attention: To better understand how the ESP32 sends data to a web server and processes the server’s response when running the example code below, please check out the following webpage. It provides detailed information about the POST request data and the responses from the httpbin.org web server.
/*
* Author: Avant Maker
* Date: February 23, 2025
* Version: 1.0
* Description: This example code demonstrates how to
* use the ESP32 HTTPClient Library's addHeader method to
* to add a simple "Content-Type" header and a custom
* "Code-Source" header with the value "AvantMaker" to a POST request.
* It also sends a JSON payload to httpbin.org and prints the
* server's response.
*
* 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";
const char* password = "your-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;
http.begin("http://httpbin.org/post"); // URL for testing POST requests
http.addHeader("Content-Type", "application/json"); // Add one header
http.addHeader("Code-Source", "AvantMaker"); // Add another custom header
String payload = "{\"message\":\"Hello from ESP32!\"}";
int httpCode = http.POST(payload);
if (httpCode > 0) {
String response = http.getString();
Serial.println("HTTP Code: " + String(httpCode));
Serial.println("Response: " + response);
} else {
Serial.println("Error on HTTP request");
}
http.end();
}
delay(10000); // Wait 10 seconds before the next request
}
Example 2: Advanced Usage with First and Replace Flags
This example demonstrates adding multiple headers, using the first
and replace
arguments to control their order and behavior. It sends a GET request to httpbin.org and shows how headers are reflected in the response.
/*
* Author: Avant Maker
* Date: February 23, 2025
* Version: 1.0
* Description: This example code demonstrates how to
* use the ESP32 HTTPClient Library's addHeader method to
* add multiple headers, using the first and replace arguments
* to control their order and behavior. It sends a GET request
* to httpbin.org and shows how headers are reflected
* in the response.
*
* 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";
const char* password = "your-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;
http.begin("http://httpbin.org/get"); // URL for testing GET requests
http.addHeader("Custom-Header", "InitialValue"); // Add a custom header
http.addHeader("Custom-Header", "ReplacedValue", false, true); // Replace the previous one
http.addHeader("Priority-Header", "TopPriority", true, false); // Add as first header
int httpCode = http.GET();
if (httpCode > 0) {
String response = http.getString();
Serial.println("HTTP Code: " + String(httpCode));
Serial.println("Response: " + response);
} else {
Serial.println("Error on HTTP request");
}
http.end();
}
delay(10000); // Wait 10 seconds before the next request
}
ESP32 Library Index
- ESP32 WiFi Library
- ESP32 WiFiClient Library
- ESP32 WiFiClientSecure Library
- ESP32 WebServer Library
- ESP32 HTTPClient Library
- Connection
- Request Methods
- Request Config
- Response
- Cookie
- Which ESP32 Boards are Recommended for Learners
- How to Copy Codes from AvantMaker.com
- What is SPIFFS and how to upload files to it?
- What is LIttleFS and how to upload files to it?
Ready to experiment and explore more about ESP32? Visit our website’s All About ESP32 Resources Hub, packed with tutorials, guides, and tools to inspire your maker journey. Experiment, explore, and elevate your skills with everything you need to master this powerful microcontroller platform!