ESP32 HTTPClient Library – POST

Home / References / ESP32 Library / HTTPClient

Description

The POST method in the ESP32 HTTPClient library is a powerful tool for sending data to a web server using the HTTP protocol. Whether you’re uploading sensor readings, submitting form data, or interacting with an API, this method enables your ESP32 to communicate effectively in IoT projects. It simplifies the process of crafting HTTP POST requests by abstracting low-level socket details, making it an essential feature for DIY enthusiasts and developers exploring IoT innovation.

ESP32 HTTP POST Request Infographic
ESP32 HTTP POST Request Infographic

Syntax and Usage

The POST method is invoked on an HTTPClient object after initializing a connection with begin(). Below are the different ways to use this method, depending on the data format you wish to send:

Using a String Argument

int httpCode = http.POST("key=value");

Sends the data as a single string, ideal for simple payloads like URL-encoded data or plain text.int httpCode = http.POST("key=value");

Using a Byte Array with Length

int httpCode = http.POST(data, length);

Sends raw binary data, such as a buffer, by specifying the data pointer and its length. Useful for custom or non-string data formats.


Argument(s)

The POST method can accept different arguments based on the usage scenario. Here’s a detailed breakdown:

  • String body
    A string containing the data to be sent in the POST request body (e.g., "key=value" or a JSON string). This is typically used with a content type like application/x-www-form-urlencoded or application/json.
  • uint8_t* data, size_t length
    A pointer to a byte array (uint8_t*) and its size (size_t). This allows sending raw binary data, offering flexibility for advanced applications.

Return Value

The POST method returns an integer representing the HTTP response code from the server. Common values include:

  • 200: Success (OK)
  • 400: Bad Request (invalid data or syntax)
  • 404: Not Found (server endpoint unavailable)
  • Negative values: Error codes indicating a failure in the request (e.g., connection issues).

Checking this return value is crucial for debugging and ensuring your request was processed correctly.

For a complete list of Return Values please refer to ESP32 HTTPClient Library – HTTP Status Codes and Error Codes


Example Codes

Example 1: POST String
This example demonstrates how to use the POST method to send data to a website, https://httpbin.org/post. The httpbin.org service is a free tool designed for testing HTTP requests—it accepts your POST data and responds with a JSON object containing what you sent, making it perfect for learning and debugging.

In this code, the ESP32 sends a simple URL-encoded string (device=ESP32&user=AvantMaker) to simulate reporting device status to a server. The response from the server is then printed to the Serial Monitor for you to inspect.

To use this example, replace YOUR_SSID and YOUR_PASSWORD with your Wi-Fi credentials, upload the code to your ESP32, and open the Serial Monitor at 115200 baud to see the results. This is an excellent starting point for IoT projects that need to communicate with live web services.

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.

Understanding How Your ESP32 Sends the HTTP POST Request

/*
 * Author: Avant Maker
 * Date: February 21, 2025
 * Version: 1.0
 * Description: This example code demonstrates how to 
 * use the ESP32 HTTPClient Library's POST to send data 
 * to https://httpbin.org/post. 
 * The httpbin.org service is a free tool designed for testing 
 * HTTP requests—it accepts your POST data and responds with a
 * JSON object containing what you sent. 
 *
 * 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");
}

void loop() {
    if (WiFi.status() == WL_CONNECTED) {
        HTTPClient http;
        http.begin("https://httpbin.org/post"); // Real public endpoint
        http.addHeader("Content-Type", "application/x-www-form-urlencoded");

        // Simple key-value data to send
        String postData = "device=ESP32&user=AvantMaker";
        int httpCode = http.POST(postData);

        if (httpCode > 0) {
            Serial.printf("HTTP Response Code: %d\n", httpCode);
            if (httpCode == HTTP_CODE_OK) { // 200
                String response = http.getString();
                Serial.println("Server Response:");
                Serial.println(response);
            }
        } else {
            Serial.printf("POST failed, error: %s\n", http.errorToString(httpCode).c_str());
        }
        http.end();
    }
    delay(20000); // Send POST every 20 seconds
}

Example 2: POST byte array with a specified size
Below is a demo code for the ESP32 HTTPClient Library’s POST method, specifically using the int POST(uint8_t *payload, size_t size) variant. This version of the POST method sends a payload as a byte array (uint8_t *) with a specified size, which is ideal for transmitting raw binary data or non-string payloads.

/*
 * Author: Avant Maker
 * Date: February 21, 2025
 * Version: 1.0
 * Description: This example code demonstrates how to 
 * use the ESP32 HTTPClient Library's POST to send a 
 * payload as a byte array (uint8_t *) with a specified
 * size, which is ideal for transmitting raw binary 
 * data or non-string payloads. 
 *
 * 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>

// WiFi credentials
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";

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

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

    // Initialize HTTPClient
    HTTPClient http;

    // Specify the URL
    http.begin("https://httpbin.org/post");

    // Set content type header (optional, depending on payload type)
    http.addHeader("Content-Type", "application/octet-stream");

    // Define the payload as a byte array
    uint8_t payload[] = {0x50, 0x6F, 0x73, 0x74, 0x20, 0x66, 0x72, 0x6F, 0x6D, 0x20, 0x45, 0x53, 0x50, 0x33, 0x32}; // "Post from ESP32" in ASCII
    size_t payloadSize = sizeof(payload);

    // Send POST request with byte array payload
    int httpCode = http.POST(payload, payloadSize);

    // Check the response
    if (httpCode > 0) {
        Serial.printf("POST request succeeded with code: %d\n", httpCode);
        String response = http.getString();
        Serial.println("Server response: " + response);
    } else {
        Serial.printf("POST request failed, error: %s\n", http.errorToString(httpCode).c_str());
    }

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

void loop() {
    // Do nothing in loop
}
error: Content is protected !!