ESP32 HTTPClient Library – setConnectTimeout

Home / References / ESP32 Library / HTTPClient

Description

The setConnectTimeout method in the ESP32 HTTPClient Library is used to set the timeout duration (in milliseconds) for establishing a connection to a server. This is particularly useful in IoT projects where you want to control how long the ESP32 waits before giving up on a connection attempt, ensuring your application remains responsive even if the server is unreachable.

Please note the differences between setTimeout and setConnectTimeout in the ESP32 HTTPClient Library:

Purpose

  • setTimeout: Sets the overall timeout for the HTTP request operations after a connection is established, including waiting for the server to respond and reading the response data.
  • setConnectTimeout: Sets the timeout specifically for establishing the initial connection to the server (i.e., the time allowed for the TCP handshake or SSL negotiation to complete).

Scope

  • setTimeout: Applies to the entire HTTP transaction once connected, such as delays in receiving headers or body data from the server.
  • setConnectTimeout: Applies only to the connection phase, determining how long the client waits to establish a connection before giving up.

Syntax and Usage

The setConnectTimeout method is called on an HTTPClient object and requires a single argument to specify the timeout duration. Below is the syntax and how to use it:

void setConnectTimeout(int32_t connectTimeout);
  • Using the method with an argument: This is the standard way to use setConnectTimeout. You provide an integer value representing the timeout in milliseconds to customize how long the ESP32 waits for a connection.

Note: There is no variation of this method without an argument, as it is designed specifically to set the timeout value.


Argument(s)

  • connectTimeout (int32_t): The time in milliseconds that the HTTPClient will wait to establish a connection to the server. A value of 0 or a negative value may result in the default timeout being used (typically 5000ms, as defined by HTTPCLIENT_DEFAULT_TCP_TIMEOUT in the library). Recommended values are positive integers, such as 1000 (1 second) or 5000 (5 seconds), depending on your application’s needs.

Return Value

The setConnectTimeout method does not return a value (it has a void return type). It simply configures the connection timeout for the HTTPClient instance, and the effect is observed when you attempt a connection using methods like begin() or GET().


Example Codes

Below is an example demonstrating how to use the setConnectTimeout method in a practical scenario.

Example: Setting a Custom Connection Timeout

This example shows how to use setConnectTimeout to limit the connection attempt to 2 seconds when making an HTTP GET request to www.example.com. The ESP32 connects to a Wi-Fi network and attempts to fetch a webpage, with a timeout to prevent hanging if the server is unavailable.

How to use this example: 
Replace YOUR_SSID and YOUR_PASSWORD with your Wi-Fi credentials. Upload the code to your ESP32 using the Arduino IDE. Open the Serial Monitor (115200 baud) to see the connection status and response. If www.example.com is unreachable within 2 seconds, the ESP32 will return an error code (e.g., -1 for connection refused).

/*
 * Author: Avant Maker
 * Date: February 21, 2025
 * Version: 1.0
 * Description: This example code demonstrates how to 
 * use the ESP32 HTTPClient Library's setConnectTimeout to 
 * limit the connection attempt to 2 seconds when making 
 * an HTTP GET request to www.example.com. 
 * The ESP32 connects to a Wi-Fi network and attempts to 
 * fetch a webpage, with a timeout to prevent hanging 
 * if the server is unavailable.
 *
 * 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);

    // Wait for Wi-Fi connection
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println("Connected to WiFi");

    // Create HTTPClient object
    HTTPClient http;

    // Set connection timeout to 2000 milliseconds (2 seconds)
    http.setConnectTimeout(2000);

    // Specify the URL
    http.begin("http://www.example.com");

    // Attempt to connect and perform GET request
    int httpCode = http.GET();

    // Check the result
    if (httpCode > 0) {
        String payload = http.getString();
        Serial.println("Response received:");
        Serial.println(payload);
    } else {
        Serial.print("Error on HTTP request: ");
        Serial.println(httpCode);
    }

    // End the connection
    http.end();
}

void loop() {
    // Nothing to do here
}
error: Content is protected !!