Understanding How To Make Post Request Using Nodemcu

Guide for making POST request using nodemcu. This is begineer's level tutorial on how you can post data to web server using nodemcu.


In this tutorial, I am going to post data to web server using nodemcu. This is simple example of IoT(Internet of Things). Here I am posting just random data, but it can be data coming from sensor in your case if you choose to do so or use this code snippet for your IoT projects. Below is the code sample with comments where required.



#include <ESP8266HTTPClient.h> //Including Library for making client
#include <ESP8266WiFi.h>  //Including Library for connecting to wifi
void setup() {
  Serial.begin(115200); //Serial connection for debugging
  WiFi.begin("Your_SSID", "Password_For_SSID");   //for WiFi connection

  while (WiFi.status() != WL_CONNECTED) {//Wait for the WiFI connection completion
    delay(500);
    Serial.println("Waiting for connection"); 
  }
  Serial.println("Wifi connected");
}

void loop(){
  if(WiFi.status() == WL_CONNECTED){   //Check WiFi connection status

     HTTPClient http;    //Declare object of class HTTPClient

     http.begin("http://xxx.xxx.xxx.xxx:xxxx/xxxxx");//Specify request destination
     http.addHeader("Content-Type", "text/plain");  //Specify content-type header
     http.addHeader("Content-Type", "application/x-www-form-urlencoded");
     int httpCode = http.POST("data=3");   //Send data
     String payload = http.getString();                  //Get the response payload
     http.end();  //Close connection
   }
  delay(3000); //for sending this dummy data at interval of 3 secs
}
And that's it. You can now send data to server and make different cool IoT projects.Before that you need to install nodemcu library for arduino IDE. You can follow this tutorial for installation. Happy IoT coding and enjoy!!!

No comments:

Post a Comment