ESP32 HTTPClient Library – begin

Home / References / ESP32 Library / HTTPClient

Description

The begin method of the ESP32 HTTPClient Library initializes an HTTP connection to a specified server or URL. This method is the first step in setting up an HTTP request, such as GET or POST, using the ESP32. It prepares the HTTPClient object to communicate with a web server by establishing the connection parameters, such as the URL or host details. This method must be called before sending any HTTP requests.


Syntax and Usage

The begin method can be used in multiple ways depending on how you want to specify the connection details. Below are the different syntaxes available:

Using a single URL string:

bool begin(String url);

This is the simplest way to initialize the HTTP connection by providing the full URL of the target server.

Using host, port, and URI::

bool begin(String host, uint16_t port, String uri);

This version allows specifying the server components separately. The URI is optional and defaults to “/”.

bool begin(WiFiClient &client, String url);

This version allows you to pass a WiFiClient object (or WiFiClientSecure for HTTPS) along with the URL, giving more control over the network client.

Using detailed host parameters:

bool begin(WiFiClient &client, String host, uint16_t port, String uri = "/", bool https = false);

This method provides granular control by specifying the host, port, URI, and protocol (HTTP or HTTPS) separately.


Argument(s)

The begin method can take different arguments depending on the usage. Below is a description of each possible argument:

  • url (String): The full URL of the server (e.g., “http://www.avantmaker.com”). Used in the single-argument version.
  • client (WiFiClient &): A reference to a WiFiClient or WiFiClientSecure object for managing the network connection. Required in multi-argument versions.
  • host (String): The hostname or IP address of the server (e.g., “www.avantmaker.com”). Used in the detailed parameters version.
  • port (uint16_t): The port number to connect to (e.g., 80 for HTTP, 443 for HTTPS). Used in the detailed parameters version.
  • uri (String): The resource path on the server (e.g., “/index.html”). Defaults to “/” if not specified. Used in the detailed parameters version.
  • https (bool): A flag to indicate whether to use HTTPS (true) or HTTP (false). Defaults to false. Used in the detailed parameters version.

Return Value

The begin method returns a bool value:

– true: The connection was successfully initialized.

– false: The initialization failed (e.g., invalid URL, network issues, or incorrect parameters).


Example Codes

Example 1: Simple HTTP GET Request with Single URL
Description: This example demonstrates the simplest usage of the begin method by providing a single URL string (“http://www.httpbin.org/get“). It performs an HTTP GET request and prints the response to the Serial Monitor. This is ideal for quick setups where you don’t need detailed control over the client.

To use this code, replace “your_SSID” and “your_PASSWORD” with your actual Wi-Fi credentials. Upload the code to your ESP32 board and open the Serial Monitor to observe the connection process and HTTP response. Ensure the target URL is accessible and adjust the delay time if faster or slower requests are needed.

/*
 * Author: Avant Maker
 * Date: February 21, 2025
 * Version: 1.0
 * Description: This example code demonstrates how to 
 * use the ESP32 HTTPClient Library's begin method by 
 * providing a single URL string ("http://www.httpbin.org/get"). 
 * It performs an HTTP GET request and prints the response 
 * to the Serial Monitor. 
 *
 * 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";          // Replace with your Wi-Fi SSID
const char* password = "your_PASSWORD";  // Replace with your Wi-Fi password

void setup() {
  Serial.begin(115200);
  delay(1000);

  Serial.print("Connecting to WiFi: ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nWiFi connected!");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;

    // Specify target URL
    String url = "http://www.httpbin.org/get";
    Serial.print("Initializing HTTP request to: ");
    Serial.println(url);

    // Use the begin(url) method
    if (http.begin(url)) { // Returns true on success
      Serial.println("HTTP begin successful.");

      // Start connection and send HTTP header
      int httpCode = http.GET();

      // httpCode will be negative on error
      if (httpCode > 0) {
        // HTTP header has been send and Server response header has been handled
        Serial.printf("[HTTP] GET... code: %d\n", httpCode);

        // file found at server
        if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
          String payload = http.getString();
          Serial.println("[HTTP] Response payload:");
          Serial.println(payload);
        }
      } else {
        Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
      }

      http.end(); // Free resources
      Serial.println("HTTP connection closed.");

    } else {
      Serial.println("HTTP begin failed!");
    }

  } else {
    Serial.println("WiFi Disconnected. Trying to reconnect...");
    WiFi.begin(ssid, password); // Attempt to reconnect
    delay(5000); // Wait before retrying loop
    return; // Skip the rest of the loop iteration
  }

  delay(30000); // Wait 30 seconds before next request
}

Example 2: Include query parameters directly in the URL

This code demonstrates the ESP32 HTTPClient Library’s begin() method by showing how to include query parameters directly in the URL. The example sends an HTTP GET request to a server using a URL with predefined query parameters, such as “avantmaker=HelloEsp32”. This illustrates that customization of the request can be handled within the URL passed to the begin() method, rather than through separate arguments in the GET call.

To use this code, replace “your_SSID” and “your_PASSWORD” with your Wi-Fi credentials. Upload the code to your ESP32 board and open the Serial Monitor to view the connection process and server response. If needed, modify the URL in the serverUrl variable to include different query parameters or target a different server.

/*
 * Author: Avant Maker
 * Date: February 21, 2025
 * Version: 1.0
 * Description: This code demonstrates the ESP32 HTTPClient
 * Library's begin() method by showing how to include query
 * parameters directly in the URL.
 *
 * 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>

// Replace with your network credentials
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";

// Target URL with query parameters (using httpbin.org/get)
const char* serverUrl = "http://httpbin.org/get?avantmaker=HelloEsp32";

void setup() {
  // Initialize Serial Monitor
  Serial.begin(115200);

  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  Serial.println("Connecting to Wi-Fi...");
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("Connected to Wi-Fi!");
  Serial.println("IP Address: ");
  Serial.println(WiFi.localIP());

  // Make the HTTP GET request
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;

    // Specify the URL with query parameters
    http.begin(serverUrl); 

    // Send the GET request
    int httpResponseCode = http.GET();

    if (httpResponseCode > 0) {
      Serial.printf("HTTP GET request code: %d\n", httpResponseCode);

      // Read and print the response
      String payload = http.getString();
      Serial.println("Response payload:");
      Serial.println(payload);
    } else {
      Serial.printf("Error in HTTP GET request: %d\n", httpResponseCode);
    }

    // Free resources
    http.end();
  }
}

void loop() {
  // Nothing to do here
}

Example 3: Using `begin()` with Host, Port, and URI

This code demonstrates how to use the ESP32 HTTPClient Library’s begin() method to initialize an HTTP request by specifying the host, port, and URI separately. It connects to a Wi-Fi network and sends an HTTP GET request to a target server using the begin(host, port, uri) method. The response from the server is then processed and displayed in the Serial Monitor.

To use this code, replace “YOUR_WIFI_SSID” and “YOUR_WIFI_PASSWORD” with your actual Wi-Fi credentials. Upload the code to your ESP32 board and open the Serial Monitor to view the connection process and HTTP response. Ensure the target host and URI are correct, and adjust the delay time if you need faster or slower requests.

/*
 * Author: Avant Maker
 * Date: February 21, 2025
 * Version: 1.0
 * Description: This example code demonstrates how to 
 * use the ESP32 HTTPClient Library's begin method by 
 * providing arguments host, port, and uri to it.
 * It performs an HTTP GET request and prints the response 
 * to the Serial Monitor. 
 *
 * 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_WIFI_SSID";
const char* password = "YOUR_WIFI_PASSWORD";

void setup() {
  Serial.begin(115200);
  delay(1000);

  Serial.print("Connecting to WiFi: ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nWiFi connected!");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;

    // Specify target server components
    const char* host = "www.httpbin.org";
    uint16_t port = 80; // Default HTTP port
    const char* uri = "/get";

    Serial.printf("Initializing HTTP request to host: %s, port: %d, uri: %s\n", host, port, uri);

    // Use the begin(host, port, uri) method
    if (http.begin(host, port, uri)) { // Returns true on success
      Serial.println("HTTP begin successful.");

      // Start connection and send HTTP header
      int httpCode = http.GET();

      // httpCode will be negative on error
      if (httpCode > 0) {
        Serial.printf("[HTTP] GET... code: %d\n", httpCode);

        if (httpCode == HTTP_CODE_OK) {
          String payload = http.getString();
          Serial.println("[HTTP] Response payload:");
          Serial.println(payload);
        }
      } else {
        Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
      }

      http.end(); // Free resources
      Serial.println("HTTP connection closed.");

    } else {
      Serial.println("HTTP begin failed!");
    }

  } else {
    Serial.println("WiFi Disconnected. Trying to reconnect...");
    WiFi.begin(ssid, password); // Attempt to reconnect
    delay(5000); // Wait before retrying loop
    return; // Skip the rest of the loop iteration
  }

  delay(30000); // Wait 30 seconds before next request
}

Example 4: HTTPS Request Using a WiFiClient and URL
This example uses the begin method with a WiFiClient object and a URL (“http://www.example.com”) to perform an HTTP GET request. This method provides control over the network client while keeping the connection simple and unsecured (HTTP), making it suitable for basic HTTP requests where encryption is not required.

/*
 * Author: Avant Maker
 * Date: February 21, 2025
 * Version: 1.0
 * Description: This example code demonstrates how to 
 * use the ESP32 HTTPClient Library's begin method with 
 * a WiFiClient object and a URL ("http://www.example.com") 
 * to perform an HTTP GET request. This method provides 
 * control over the network client while keeping the connection 
 * simple and unsecured (HTTP), making it suitable for basic 
 * HTTP requests where encryption is not required.
 *
 * 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("Connected to WiFi");

    WiFiClient client;  // Using WiFiClient instead of WiFiClientSecure
    HTTPClient http;
    if (http.begin(client, "http://www.example.com")) {  // WiFiClient and URL
        int httpCode = http.GET();
        if (httpCode > 0) {
            String payload = http.getString();
            Serial.println("Response: " + payload);
        } else {
            Serial.println("GET request failed");
        }
        http.end();
    } else {
        Serial.println("Unable to connect");
    }
}

void loop() {
    // Nothing here
}

Example 5: Using Detailed Host Parameters
This example uses the begin method with detailed parameters—specifying the host (“www.example.com”), port (80), and URI (“/index”)—to connect to a custom server endpoint. This approach is useful when you need precise control over the connection details, such as connecting to non-standard ports or specific paths.

/*
 * Author: Avant Maker
 * Date: February 21, 2025
 * Version: 1.0
 * Description: This example code demonstrates how to 
 * use the ESP32 HTTPClient Library's begin method with 
 * detailed parameters—specifying the host ("www.example.com"), 
 * port (80), and URI ("/index")—to connect to a custom 
 * server endpoint.
 *
 * 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("Connected to WiFi");

    WiFiClient client;
    HTTPClient http;
    if (http.begin(client, "www.example.com", 80, "/index/")) {  // Detailed parameters
        int httpCode = http.GET();
        if (httpCode > 0) {
            String payload = http.getString();
            Serial.println("Response: " + payload);
        } else {
            Serial.println("GET request failed");
        }
        http.end();
    } else {
        Serial.println("Unable to connect");
    }
}

void loop() {
    // Nothing here
}

Example 6: HTTPS Request with WiFiClientSecure
This example uses the begin method with a WiFiClientSecure object to make a secure HTTPS GET request to www.example.com.

/*
 * Author: Avant Maker
 * Date: February 21, 2025
 * Version: 1.0
 * Description: This example code demonstrates how to 
 * use the ESP32 HTTPClient Library's begin method with a WiFiClientSecure
 * object to make a secure HTTPS GET request to www.example.com.
 *
 * 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>
#include <WiFiClientSecure.h>

// const char* ssid = "YOUR_SSID";
// const char* password = "YOUR_PASSWORD";
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("Connected to WiFi");

    WiFiClientSecure client;
    client.setInsecure();  // Skip certificate verification for simplicity
    HTTPClient http;
    if (http.begin(client, "https://www.example.com")) {  // WiFiClient and URL
        int httpCode = http.GET();
        if (httpCode > 0) {
            String payload = http.getString();
            Serial.println("Response: " + payload);
        } else {
            Serial.println("GET request failed");
        }
        http.end();
    } else {
        Serial.println("Unable to connect");
    }
}

void loop() {
    // Nothing here
}

Example 7: Advanced HTTP Request with Custom Headers

This example demonstrates how to use the begin() method with additional configuration such as setting custom headers.

/*
 * Author: Avant Maker
 * Date: February 21, 2025
 * Version: 1.0
 * Description: This example code demonstrates how to 
 * use the ESP32 HTTPClient Library's begin method with
 * additional configuration such as setting custom headers.
 *
 * 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";          // Replace with your Wi-Fi SSID
const char* password = "your_PASSWORD";  // Replace with your Wi-Fi password

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  
  Serial.println("");
  Serial.println("WiFi connected");
  
  HTTPClient http;
  
  // Begin with URL
  http.begin("http://www.httpbin.org/headers");
  
  // Set custom headers
  http.addHeader("Content-Type", "application/json");
  http.addHeader("User-Agent", "ESP32-HTTPClient/1.0");
  http.addHeader("X-Custom-Header", "AvantMaker.com Example");
  
  // Make GET request
  int httpCode = http.GET();
  
  // Check the response
  if (httpCode > 0) {
    Serial.printf("HTTP Response code: %d\n", httpCode);
    String payload = http.getString();
    Serial.println(payload);
  } else {
    Serial.printf("HTTP Request failed, error: %s\n", http.errorToString(httpCode).c_str());
  }
  
  http.end();
}

void loop() {
}
error: Content is protected !!