ESP32 HTTPClient Library – setUserAgent

Home / References / ESP32 Library / HTTPClient

Description

The setUserAgent method in the ESP32 HTTPClient Library allows you to define the User-Agent string sent in the HTTP request headers. The User-Agent identifies your application or device to the server, which can be useful for debugging, server-side analytics, or meeting API requirements. For makers and enthusiasts, this method adds a layer of personalization and control to your ESP32 projects when communicating with web services.


Syntax and Usage

The setUserAgent method has a single, straightforward usage. It’s called before sending an HTTP request to set a custom User-Agent string. Here’s how it’s used:

  • With a User-Agent String: Pass a string that identifies your client (e.g., your project name, ESP32 device, or a custom identifier). This string will be included in the HTTP request headers.

If not set, the default User-Agent is typically determined by the underlying HTTP client implementation (e.g., “ESP32-http-Client”). Using this method overrides that default.

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 setUserAgent method requires one argument. Here’s the detail:

  • userAgent: A null-terminated C-string (const char *) specifying the User-Agent string. Examples might include:
    • "AvantMaker-Project": A custom identifier for your project.
    • "AvantMaker-ESP32/1.0": A versioned identifier for your application.
    You can use any string that suits your needs or meets server expectations.

Return Value

The setUserAgent method does not return a value (i.e., its return type is void). It modifies the internal configuration of the HTTPClient object, setting the User-Agent header for subsequent HTTP requests.


Example Codes

Below is an example demonstrating how to use setUserAgent in a practical scenario. This example connects to www.httpbin.org, a free testing service that echoes back request headers, allowing you to see the custom User-Agent in action.

Example: Setting a Custom User-Agent for an HTTP Request

This example shows how to use setUserAgent to identify the ESP32 as a custom client (“AvantMaker-ESP32”) when making a GET request to httpbin.org. The server’s response includes the User-Agent, which we print to the Serial Monitor.

/*
 * Author: Avant Maker
 * Date: February 23, 2025
 * Version: 1.0
 * Description: This example code demonstrates how to 
 * use the ESP32 HTTPClient Library's sendRequest method to 
 * identify the ESP32 as a custom client ("AvantMaker-ESP32")
 * when making a GET request.
 * 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("https://httpbin.org/get"); // Endpoint that returns request headers
        http.setUserAgent("AvantMaker-ESP32"); // Custom User-Agent string
        
        int httpCode = http.GET();
        if (httpCode > 0) {
            String payload = http.getString();
            Serial.println("Response Code: " + String(httpCode));
            Serial.println("Response: " + payload); // Look for "User-Agent" in the JSON response
        } else {
            Serial.println("Error on HTTP request: " + String(httpCode));
        }
        http.end();
    }
    delay(10000); // Wait 10 seconds before the next request
}

In the response from httpbin.org, you’ll see the “User-Agent” field reflect “AvantMaker-ESP32”. Try experimenting with different User-Agent strings to see how servers respond, or use it to meet specific API requirements in your projects!

error: Content is protected !!