Send POST Request using ESP8266 NodeMCU

POST is one of the HTTP methods which is used to send data to a server to create a resource. The ESP8266 is a chip that has a full TCP/IP protocol stack. The ESP8266 is able to send requests and retrieve responses from a server using the HTTP protocol.

This tutorial provides example how to send POST request using ESP8266 NodeMCU development board.

Components

No.ComponentQuantity
1.ESP8266 NodeMCU + Micro USB cable1

Code

There are three defined constants that stores Wi-Fi network credentials (SSID and password) and a server URL. In order to send POST request an instance of HTTPClient class is created. In the setup function serial communication is initialized and connection is established to a Wifi network.

A request sending is implemented in the loop function. The begin method is used to parse URL. A HTTP header can be added to the request with addHeader method. In this case, Content-Type is application/x-www-form-urlencoded. It means that data are encoded in key-value pairs separated by &, with a = between the key and the value. POST request is send to the server with POST method. The body of the request is passed as argument. The getString method allows to read response content. The TCP connection is closed by invoking the end method.

#include <Arduino.h>

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

const char *WIFI_SSID = "YOUR WIFI NETWORK NAME";
const char *WIFI_PASSWORD = "YOUR WIFI PASSWORD";
const char *URL = "http://httpbin.org/post";

WiFiClient client;
HTTPClient httpClient;

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

    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }

    Serial.println("Connected");
}

void loop()
{
    String data = "name=John&age=20";

    httpClient.begin(client, URL);
    httpClient.addHeader("Content-Type", "application/x-www-form-urlencoded");
    httpClient.POST(data);
    String content = httpClient.getString();
    httpClient.end();

    Serial.println(content);
    delay(5000);
}

Leave a Comment

Your email address will not be published. Required fields are marked *