Post example

/*
* HTTPS Secured Client POST Request
* Copyright (c) 2019, circuits4you.com
* All rights reserved.
* https://circuits4you.com
* Connects to WiFi HotSpot. */
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
/* Set these to your desired credentials. */
const char *ssid = "your_ssid";  //ENTER YOUR WIFI SETTINGS
const char *password = "your_pass";
//Link to read data from https://jsonplaceholder.typicode.com/comments?postId=7
//Web/Server address to read/write from
const char *host = "postman-echo.com";
const int httpsPort = 443;  //HTTPS= 443 and HTTP = 80
//SHA1 finger print of certificate use web browser to view and copy
const char fingerprint[] PROGMEM = "A6 5A 41 2C 0E DC FF C3 16 E8 57 E9 F2 C3 11 D2 71 58 DF D9";
//=======================================================================
//                    Power on setup
//=======================================================================
void setup() {
  delay(1000);
  Serial.begin(115200);
  WiFi.mode(WIFI_OFF);        //Prevents reconnection issue (taking too long to connect)
  delay(1000);
  WiFi.mode(WIFI_STA);        //Only Station No AP, This line hides the viewing of ESP as wifi hotspot
  
  WiFi.begin(ssid, password);     //Connect to your WiFi router
  Serial.println("");
  Serial.print("Connecting");
  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  //If connection successful show IP address in serial monitor
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());  //IP address assigned to your ESP
}
//=======================================================================
//                    Main Program Loop
//=======================================================================
void loop() {
  WiFiClientSecure httpsClient;    //Declare object of class WiFiClient
  Serial.println(host);
  Serial.printf("Using fingerprint '%s'\n", fingerprint);
  httpsClient.setFingerprint(fingerprint);
  httpsClient.setTimeout(15000); // 15 Seconds
  delay(1000);
  
  Serial.print("HTTPS Connecting");
  int r=0; //retry counter
  while((!httpsClient.connect(host, httpsPort)) && (r < 30)){
      delay(100);
      Serial.print(".");
      r++;
  }
  if(r==30) {
    Serial.println("Connection failed");
  }
  else {
    Serial.println("Connected to web");
  }
  
  String getData, Link;
  
  //POST Data
  Link = "/post";
  Serial.print("requesting URL: ");
  Serial.println(host);
  /*
   POST /post HTTP/1.1
   Host: postman-echo.com
   Content-Type: application/x-www-form-urlencoded
   Content-Length: 13
  
   say=Hi&to=Mom
    
   */
  httpsClient.print(String("POST ") + Link + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Content-Type: application/x-www-form-urlencoded"+ "\r\n" +
               "Content-Length: 13" + "\r\n\r\n" +
               "say=Hi&to=Mom" + "\r\n" +
               "Connection: close\r\n\r\n");
  Serial.println("request sent");
                  
  while (httpsClient.connected()) {
    String line = httpsClient.readStringUntil('\n');
    if (line == "\r") {
      Serial.println("headers received");
      break;
    }
  }
  Serial.println("reply was:");
  Serial.println("==========");
  String line;
  while(httpsClient.available()){        
    line = httpsClient.readStringUntil('\n');  //Read Line by Line
    Serial.println(line); //Print response
  }
  Serial.println("==========");
  Serial.println("closing connection");
    
  delay(2000);  //POST Data at every 2 seconds
}
//=======================================================================

Upload the code and open serial monitor, in

client.print(String("POST ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n"+ "Content-Length: " + data.length() + "\r\n" + "Content-Type: application/json;charset=UTF-8\r\n\r\n"+ data +"\r\n");



String postRequest =
"POST " + uri + " HTTP/1.0\r\n" +
"Host: " + server + "\r\n" +
"Accept: *" + "/" + "*\r\n" +
"Content-Length: " + data.length() + "\r\n" +
"Content-Type: application/x-www-form-urlencoded\r\n" +

"\r\n" + data;


#include <ESP8266HTTPClient.h> // head of program

const char *host = "http://URL to page";

// Below in the Loop
HTTPClient http;    //Declare object of class HTTPClient

  //Post Data
  String postData = "data=" + data ;

  http.begin(host);              //Specify request destination
  delay(1000); // See if this prevents the problm with connection refused and deep sleep
  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.println(httpCode);   //Print HTTP return code
  Serial.println(payload);    //Print request response payload

  http.end();  //Close connection
1
2
3
4
5
6
7
8
9
POST /esppost.php HTTP/1.0
Host: serverconnect.site88.net
Accept: */*
Content-Length: "name1=value1&name2=value2".Length
Content-Type: application/x-www-form-urlencoded

name1=value1&name2=value2


Code

1) Include the ESP8266WiFi library and initialize variables for hardware and data collection. Edit the network information and write API key in your code.
#include <ESP8266WiFi.h>

// Network information.
#define WIFI_NAME "YOUR_WIFI_NAME"
#define PASSWORD "WIFI_PASSWORD"

// Hardware information.
#define SENSOR_POWER 13                            // Connect the power for the soil sensor here.
#define SOIL_PIN A0                                // Connect the sensor output pin here.
#define TIMEOUT  5000                              // Timeout for server response.
#define SLEEP_TIME_SECONDS 1800

// ThingSpeak information.
#define NUM_FIELDS 2                               // To update more fields, increase this number and add a field label below.
#define SOIL_MOISTURE_FIELD 1                      // ThingSpeak field for soil moisture measurement.
#define ELAPSED_TIME_FIELD 2                       // ThingSpeak field for elapsed time from startup.
#define THING_SPEAK_ADDRESS "api.thingspeak.com"
String writeAPIKey="XXXXXXXXXXXXXXXX";             // Change this to the write API key for your channel.

// Global variables. 
int numMeasure = 5;                                // Number of measurements to average.
int ADCValue = 0;                                  // Moisture sensor reading.
                         
WiFiClient client;
2) In the setup function, start the serial monitor, connect to the wireless network, and initialize the device pins that you use.
// Put your setup code here, to run once:
void setup()
{
    Serial.begin( 115200 );   // You may need to adjust the speed depending on your hardware.
    connectWifi();
    pinMode( SENSOR_POWER , OUTPUT );
    digitalWrite( SENSOR_POWER , LOW );   // Set to LOW so no power is flowing through the sensor.
}
3) In the main loop, read the soil monitor and store it in the data array. POST the data to ThingSpeak, and then put the device in low-power mode.
// Put your main code here, to run repeatedly:
void loop()
{
    // Write to successive fields in your channel by filling fieldData with up to 8 values.
    String fieldData[ NUM_FIELDS ];  

    // You can write to multiple fields by storing data in the fieldData[] array, and changing numFields.        
    // Write the moisture data to field 1.
    fieldData[ SOIL_MOISTURE_FIELD ] = String( readSoil( numMeasure ) ); 
    Serial.print( "Soil Moisture = " );
    Serial.println( fieldData[ SOIL_MOISTURE_FIELD ] );
    
    // Write the elapsed time from startup to Field 2.
    fieldData[ ELAPSED_TIME_FIELD ] = String( millis() ); 
    
    HTTPPost( NUM_FIELDS , fieldData );
    
    delay( 1000 );
    Serial.print( "Goodnight for "+String( SLEEP_TIME_SECONDS ) + " Seconds" );
    ESP.deepSleep( SLEEP_TIME_SECONDS * 1000000 );
    // If you disable sleep mode, add delay so you don't post to ThingSpeak too often.
    // delay( 20000 );
}
4) Use the readSoil function to provide power to the sensor, and then read the voltage at the output using the ADC. Turn off the power after measurement.
// This function reads the soil moisture sensor numAve times and returns the average.
long readSoil(int numAve)
{
  long ADCValue = 0;
  
  for ( int i = 0; i < numAve; i++ ) {
    digitalWrite( SENSOR_POWER, HIGH );  // Turn power to device on.
    delay(10);    // Wait 10 milliseconds for sensor to settle.
    ADCValue += analogRead( SOIL_PIN );     // Read the value from sensor.
    digitalWrite( SENSOR_POWER, LOW );   // Turn power to device off.
  }
  
  ADCValue = ADCValue / numAve;
  return ADCValue;                    // Return the moisture value.
}
5) Connect your device to the wireless network using the connectWiFi function.
// Connect to the local Wi-Fi network
int connectWifi()
{
    
    while (WiFi.status() != WL_CONNECTED) {
        WiFi.begin( WIFI_NAME , PASSWORD );
        Serial.println( "Connecting to Wi-Fi" );
        delay( 2500 );
    }
    Serial.println( "Connected" );  // Inform the serial monitor.
}
6) Build the data string to post to your channel. Connect to ThingSpeak, and use the Wi-Fi client to complete an HTTP POST.
// This function builds the data string for posting to ThingSpeak
    // and provides the correct format for the wifi client to communicate with ThingSpeak.
    // It posts numFields worth of data entries, and takes the
    // data from the fieldData parameter passed to it. 
  
int HTTPPost( int numFields , String fieldData[] ){
  
    if (client.connect( THING_SPEAK_ADDRESS , 80 )){

       // Build the postData string.  
       // If you have multiple fields, make sure the sting does not exceed 1440 characters.
       String postData= "api_key=" + writeAPIKey ;
       for ( int fieldNumber = 1; fieldNumber < numFields+1; fieldNumber++ ){
            String fieldName = "field" + String( fieldNumber );
            postData += "&" + fieldName + "=" + fieldData[ fieldNumber ];
            
            }

        // POST data via HTTP.
        Serial.println( "Connecting to ThingSpeak for update..." );
        Serial.println();
        
        client.println( "POST /update HTTP/1.1" );
        client.println( "Host: api.thingspeak.com" );
        client.println( "Connection: close" );
        client.println( "Content-Type: application/x-www-form-urlencoded" );
        client.println( "Content-Length: " + String( postData.length() ) );
        client.println();
        client.println( postData );
        
        Serial.println( postData );
        
        String answer=getResponse();
        Serial.println( answer );
    }
    else
    {
      Serial.println ( "Connection Failed" );
    }
    
}
7) Wait for and receive the response from the server using getResponse.
// Wait for a response from the server indicating availability,
// and then collect the response and build it into a string.

String getResponse(){
  String response;
  long startTime = millis();

  delay( 200 );
  while ( client.available() < 1 && (( millis() - startTime ) < TIMEOUT ) ){
        delay( 5 );
  }
  
  if( client.available() > 0 ){ // Get response from server.
     char charIn;
     do {
         charIn = client.read(); // Read a char from the buffer.
         response += charIn;     // Append the char to the string response.
        } while ( client.available() > 0 );
    }
  client.stop();
        
  return response;
}

Comments

Popular posts from this blog

Flutter for Single-Page Scrollable Websites with Navigator 2.0

A Data Science Portfolio is More Valuable than a Resume

Better File Storage in Oracle Cloud