HTTP GET and POST Protocol with ESP8266

Today in this tutorial I will show you HTTP GET and POST Protocol with ESP8266 step by step complete process.

HTTP is the underlying protocol utilized by the World Wide Web. This protocol defines how communications formatted and transmitted. In this tutorial With the help of HTTP, we look for more web-related functions such as serving HTML web pages, redirect. And also know how to work HTTP Protocol  GET and POST with ESP8266.


≡ Required Component :


Here is a list of the hardware we HTTP GET and POST Protocol with ESP8266.

  1. NodeMcu8266
  2. Breadboard
  3. Connecting wire
  4. Breadboard Power Supply Module

≡ Program for sending text:


For web server requires a library. Its object is defined using the ESP8266WebServer server(80). After defining objects in setup define uses to handle web requests present on the root.

server.on(“/”, handleRoot);

The “/” represents root location i.e. IP address, next to that start the webserver utilizing server.begin(). In the loop, we have to handle client requests using the server.handleClient(); In function to handle client requests i.e. handle root we send plain text to the web browser. 200 is the OK response

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
const char* wifiName = "Wi-Fi-name";
const char* wifiPass = "Wi-Fi-password";
ESP8266WebServer server(80);  //Define server object
//Handles http request
void handleRoot() {
  digitalWrite(2, 0);   //Blinks on board led on page request
  server.send(200, "text/plain", "hello from esp8266!");
  digitalWrite(2, 1);
}
// the setup function runs once when you press reset or power the board
void setup() {
  Serial.begin(115200);
  delay(10);
  pinMode(2,OUTPUT);
  Serial.println();
  Serial.print("Connecting");
  WiFi.begin(wifiName, wifiPass);   //Connect to Wi-Fi
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("Wi-Fi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());   //You can get IP address assigned to ESP
  server.on("/", handleRoot);      //Associate handler function to web requests
  server.begin(); //Start web server
  Serial.println("HTTP server started");
}
void loop() {
  //Handle Clinet requests
  server.handleClient();
}

If the Upload program and open your serial monitor you can see an IP Address.

Program for HTTP HTML web page

open it the web browser using IP address which is connected to the same Wi-Fi network. you Can see  “hello from esp8266 !”. Also, see board blue LED it will blink every time you request the web page from the web browser.

Program for HTTP HTML web page


Program for HTTP HTML web page


For HTML web page server configuration process is as like as used in plain text.  the difference is how we handle web page handleRoot. Instead of using text/plain, we use

server.send(200, “text/html”, htmlPage);

htmlPage” is “String” variable contains HTML code of webpage.

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
const char* wifiName = "Mechatronicslab";
const char* wifiPass = "Pa$$word";
ESP8266WebServer server(80);  //Define server object
const char htmlPage[] PROGMEM = R"=====(

<HTML>

  <HEAD>

      <TITLE>My first web page</TITLE>

  </HEAD>

<BODY>

  <CENTER>

      <B>Hello MechatronicsLAB.... </B>     

  </CENTER>

  <marquee behavior="alternate"> This Is HTTP  GET and POST Protocol with ESP8266</marquee>

</BODY>

</HTML>

)=====";
//Handles http request
void handleRoot() {
  digitalWrite(2, 0);   //Blinks on board led on page request
  server.send(200, "text/html", htmlPage);
  digitalWrite(2, 1);
}
// the setup function runs once when you press reset or power the board
void setup() {
  Serial.begin(115200);
  delay(10);
  pinMode(2,OUTPUT);
  Serial.println();
  Serial.print("Connecting");
  WiFi.begin(wifiName, wifiPass);   //Connect to Wi-Fi
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("Wi-Fi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());   //You can get IP address assigned to ESP
  server.on("/", handleRoot);      //Associate handler function to web requests
  server.begin(); //Start web server
  Serial.println("HTTP server started");
}
void loop() {
  //Handle Clinet requests
  server.handleClient();
}

Get the IP address from your serial monitor and open it in a web browser using this IP address.

Program for HTTP HTML web page


≡ HTTP Protocol GET and POST


Two protocols commonly utilized for a request-response between a client and server are GET and POST.

GET – Requests data from a specified resource
POST – Submits data to be processed to a specified resource


≡ GET


The GET Protocol requests the transfer of a current selected representation for the target resource. GET is the main tool of information retrieval and the focus of almost all special optimizations.


≡ The GET Method


the query string  sent in the URL of a GET request:

http://httpbin.org/get?name1=value1&name2=value2
POST
The POST Protocol requests that the target resource process the representation enclosed in the request according to the resource’s specific meaning. For example, POST  done for the following functions :

  1. Giving a block of data, such as the fields entered into an HTML form, to a data-handling process
  2. Posting a message to a notice board, newsgroup, mailing list, blog, or similar group of sections;
  3. Building a new resource that has yet to be known by the origin server;
  4. Adding data to a resource’s existing representation(s).

An author server indicates response meaning by choosing an appropriate status code depending on the result of processing the POST request, about all of the status codes defined by this term might receive in a response to POST, 304 (Not Modified), and 416 (Range Not Satisfiable)).


≡ The POST Protocol


The query string (name/value pairs)  sent in the HTTP message body of a POST call:

POST / HTTP/1.1
Host: foo.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 13
say=Hi&to=Mom

≡ Program  GET Request:


This program makes ESP8266 development board NodeMCU as a client to send Http request to the webserver and gets a response from it.

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
const char* wifiName = "Mechatronicslab";
const char* wifiPass = "Pa$$word";
//Web Server address to read/write from
const char *host = "http://httpbin.org/get";
void setup() {
  Serial.begin(115200);
  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(wifiName);
  WiFi.begin(wifiName, wifiPass);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("Wi-Fi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());   //You can get IP address assigned to ESP
}
void loop() {
  HTTPClient http;    //Declare object of class HTTPClient
  String ADCData = String(analogRead(A0));
  String getData, Link;
  //GET Data
  //Note "?" added at front and "&" is used after each new parameter as per GET format
  getData = "?data=" + ADCData + "&sensor=temperature"; 
  Link = host + getData;
  Serial.print("Request Link:");
  Serial.println(Link);
  http.begin(Link);     //Specify request destination
  int httpCode = http.GET();            //Send the request
  String payload = http.getString();    //Get the response payload from server
  Serial.print("Response Code:"); //200 is OK
  Serial.println(httpCode);   //Print HTTP return code
  Serial.print("Returned data from Server:");
  Serial.println(payload);    //Print request response payload
  http.end();  //Close connection
  delay(5000);  //GET Data at every 5 seconds
}

after uploading the program Open the serial monitor and observe the response. Try the same link in the web browser it should return the same response the same as we are getting in ESP serial monitor.

Program Handling GET request sent


≡ Program Handling GET request sent:


This program, we handle the GET request sent  NodeMCU from the client. 

#include <ESP8266WiFi.h>
const char* ssid = "Mechatronicslab";  // Enter SSID here
const char* password = "Pa$$word";  //Enter Password here
// Variable to store the HTTP request
String header;
String LED1State = "off";
const int LED1 = D0;
WiFiServer server(80);

void setup() {
  Serial.begin(115200);
  pinMode(LED1, OUTPUT);
  digitalWrite(LED1, LOW);
 Serial.print("Connecting to ");
 Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
    delay(500);
   Serial.print(".");
 }
// Print local IP address and start web server
 Serial.println("");
  Serial.println("WiFi connected-->");
  Serial.println("Copy this IP address: ");
  Serial.println(WiFi.localIP());
  server.begin();
}

void loop(){
  WiFiClient client = server.available();   
  if (client) {                             // If a new client connects,
    Serial.println("new client connected");          
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected())
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             
        Serial.write(c);                    
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          if (currentLine.length() == 0) {
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();

            if (header.indexOf("GET /LED1/on") >= 0) {
              Serial.println("LED1 on");
              LED1State = "on";
              digitalWrite(LED1, HIGH);
            } else if (header.indexOf("GET /LED1/off") >= 0) {
              Serial.println("LED1 off");
              LED1State = "off";
              digitalWrite(LED1, LOW);
            } 
            
            // Display the HTML web page
            client.println("<!DOCTYPE html><html>");
            client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");
            client.println("<style>html { font-family: Cairo; display: inline; margin: 0px auto; text-align: center; background-color: #918787;}");
            client.println(".button { background-color: #170099; border: none; color: white; padding: 16px 40px;");
            client.println("text-decoration: none; font-size: 35px; margin: 2px; cursor: pointer;}");
            client.println(".button2 {background-color: #555555;}</style></head>");
        
            client.println("<svg width=\"300\" height=\"80\"><text fill=\"#fa0707\" font-family=\"serif\" font-size=\"24\" id=\"svg_1\" stroke=\"#000000\" text-anchor=\"middle\" transform=\"matrix(1.35388 0 0 1.42308 -6.66283 -8.67308)\" x=\"86.5\" xml:space=\"preserve\" y=\"41.5\"> MechatronicsLAB</text></svg>");
          
            // Web Page Heading
            client.println("<body><h1>HTTP  GET and POST Protocol with ESP8266</h1>");
            client.println("<p>LED: " + LED1State + "</p>");
            // If the LED1State is off, it displays the ON button       
            if (LED1State=="off") {
              client.println("<p><a href=\"/LED1/on\"><button class=\"button\">ON</button></a></p>");
              client.println("<svg width=\"500\" height=\"300\"><ellipse cx=\"258.5\" cy=\"125.5\" fill=\"#ffffff\" rx=\"47\" ry=\"52\" stroke=\"#ffffaa\" stroke-width=\"5\"/><rect fill=\"#cccccc\" height=\"40\" stroke=\"#ffffaa\" stroke-width=\"5\" transform=\"rotate(-0.485546 261 187.5)\" width=\"39\" x=\"241.5\" y=\"167.5\"/></svg>");

            } else {
              client.println("<p><a href=\"/LED1/off\"><button class=\"button button2\">OFF</button></a></p>");
              client.println("<svg width=\"500\" height=\"300\"><ellipse cx=\"258.5\" cy=\"125.5\" fill=\"#ff7f00\" rx=\"47\" ry=\"52\" stroke=\"#ffffaa\" stroke-width=\"5\"/><rect fill=\"#cccccc\" height=\"40\" stroke=\"#ffffaa\" stroke-width=\"5\" transform=\"rotate(-0.485546 261 187.5)\" width=\"39\" x=\"241.5\" y=\"167.5\"/></svg>");

            }     
            client.println("</body></html>");
            client.println();
            break;
          } else { 
            currentLine = "";
          }
        } else if (c != '\r') {  
          currentLine += c;      
        }
      }
    }
    header = "";
    client.stop();
    Serial.println("Client disconnected");
    Serial.println("");
  }

After uploading  Open a web browser and enter IP Address

Program Handling GET request sent


≡ Program POST Request:


This program  NodeMCU as a client to send Http request to the webserver and gets the response from it.

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
const char* wifiName = "Mechatronicslab";
const char* wifiPass = "Pa$$word";
//Web Server address to read/write from
const char *host = "http://httpbin.org/post";
void setup() {
  Serial.begin(115200);
  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(wifiName);
  WiFi.begin(wifiName, wifiPass);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("Wi-Fi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());   //You can get IP address assigned to ESP
}
void loop() {
  HTTPClient http;    //Declare object of class HTTPClient
  String ADCData = String(analogRead(A0));
  String postData;
  //POST Data
  postData = "data=" + ADCData + "&sensor=temperature"; 
  Serial.print("Post Data:");
  Serial.println(postData);
  http.begin(host);   //Specify request destination
  http.addHeader("Content-Type", "application/x-www-form-urlencoded");    //Specify content-type header
  int httpCode = http.POST(postData);   //Send the request
  String payload = http.getString();    //Get the response payload
  Serial.print("Response Code:"); //200 is OK
  Serial.println(httpCode);   //Print HTTP return code
  Serial.print("Returned data from Server:");
  Serial.println(payload);    //Print request response payload
  http.end();  //Close connection
  delay(5000);  //POST Data at every 5 seconds
}

Upload the program and open your serial monitor.

Program POST Request


≡ Program to handle POST requests


The program is the same as the GET request handler but we are sending POST request using web forms. HTML web page code only modified. Button Name kept the same and its value changed while using server.arg(“LED”), use the name of the HTML form element to read the value from it. It is possible to have multiple arguments with different values.

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
 
const char ssid[] = "Mechatronicslab";
const char pass[] = "Pa$$word";
 
// Web server port
const uint16_t port = 80;
boolean ledStatus = false;
 
// Web server object declaration
ESP8266WebServer server(port);
 
String webPage =
    "<html>\r\n" \
    "<head>\r\n" \
    "<title>ESP8266 Basic Page LED</title>\r\n" \
    "</head>\r\n" \
    "<body>\r\n" \
    "<h1>LED</h1>\r\n" \
    "<form method=\"get\">\r\n" \
    "<input type=\"submit\" name=\"led\" value=\"ON\">\r\n" \
    "<input type=\"submit\" name=\"led\" value=\"OFF\">\r\n" \
    "</form>\r\n" \
    "</body>\r\n" \
    "</html>\r\n";
 
void handleRoot()
{
    // *** Turn on or off the LED ***
    if (server.arg("led") == "ON")
        digitalWrite(D4, LOW);
    else if (server.arg("led") == "OFF")
        digitalWrite(D4, HIGH);
    
    server.send(200, "text/html", webPage);
}
 
void setup()
{
    // Set pin as output
    pinMode(D4, OUTPUT);
    // Setup serial communication
    Serial.begin(74880);
 
    // *** Connect to a WiFi acces point ***
    Serial.printf("Connecting to %s ", ssid);
    WiFi.begin(ssid, pass);
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(500);
        Serial.print(".");
    }
    Serial.printf(" Connected\n");
    Serial.printf("IP address: %s\n", WiFi.localIP().toString().c_str());
 
    // *** Start web server ***
    server.on("/", HTTP_GET, handleRoot);
    server.begin();
    Serial.printf("Web server started at port %d\n", port);
}
 
void loop()
{
    server.handleClient();
}

Program to handle POST requests

Visit to get more tutorials on ESP8266

 439 total views,  13 views today