AsyncHTTPRequest_Generic example for POST DATA

Hello everyone.
I am searching for one example with this library. I found only one example:
AsyncDweetPost_STM32.ino

But deeping the the sample code i see that really is not posting, is a GET request. Adding data to the URL.

const char POST_ServerAddress[] = "dweet.io";
String dweetName = "/dweet/for/pinA0-Read?";
String postData = "sensorValue=";


requestOpenResult = request.open("POST", (POST_ServerAddress + dweetName + postData).c_str() );

The result is "dweet.io/dweet/for/pinA0-Read?sensorValue=" (all data in the URL, so is a GET.
I need send about 3k of data in post.
Thanks to all
Christian

I put the complete code here.

/****************************************************************************************************************************
  AsyncDweetPOST_STM32.ino - Dead simple AsyncHTTPRequest for ESP8266, ESP32 and currently STM32 with built-in LAN8742A Ethernet

  For ESP8266, ESP32 and STM32 with built-in LAN8742A Ethernet (Nucleo-144, DISCOVERY, etc)

  AsyncHTTPRequest_Generic is a library for the ESP8266, ESP32 and currently STM32 run built-in Ethernet WebServer

  Based on and modified from asyncHTTPrequest Library (https://github.com/boblemaire/asyncHTTPrequest)

  Built by Khoi Hoang https://github.com/khoih-prog/AsyncHTTPRequest_Generic
  Licensed under MIT license

  Copyright (C) <2018>  <Bob Lemaire, IoTaWatt, Inc.>
  This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License
  as published bythe Free Software Foundation, either version 3 of the License, or (at your option) any later version.
  This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
  You should have received a copy of the GNU General Public License along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *****************************************************************************************************************************/

// Dweet.io POST client. Connects to dweet.io once every ten seconds, sends a POST request and a request body.
// Shows how to use Strings to assemble path and body

#include "defines.h"

// Select a test server address
const char POST_ServerAddress[] = "dweet.io";

// use your own thing name here
String dweetName = "/dweet/for/pinA0-Read?";

#define ASYNC_HTTP_REQUEST_GENERIC_VERSION_MIN_TARGET      "AsyncHTTPRequest_Generic v1.10.2"
#define ASYNC_HTTP_REQUEST_GENERIC_VERSION_MIN             1010002

// 600s = 10 minutes to not flooding, 60s in testing
#define HTTP_REQUEST_INTERVAL_MS     60000  //600000

// Uncomment for certain HTTP site to optimize
//#define NOT_SEND_HEADER_AFTER_CONNECTED        true

// To be included only in main(), .ino with setup() to avoid `Multiple Definitions` Linker Error
#include <AsyncHTTPRequest_Generic.h>             // https://github.com/khoih-prog/AsyncHTTPRequest_Generic

#include <Ticker.h>                             // https://github.com/sstaub/Ticker

AsyncHTTPRequest request;

void sendRequest(void);

// Repeat forever, millis() resolution
Ticker sendHTTPRequest(sendRequest, HTTP_REQUEST_INTERVAL_MS, 0, MILLIS);

void sendRequest(void)
{
  static bool requestOpenResult;

  if (request.readyState() == readyStateUnsent || request.readyState() == readyStateDone)
  {
    String postData = "sensorValue=";
    postData += analogRead(A0);

    Serial.println("\nMaking new POST request");

    requestOpenResult = request.open("POST", (POST_ServerAddress + dweetName + postData).c_str() );

    if (requestOpenResult)
    {
      // Only send() if open() returns true, or crash
      request.send();
    }
    else
    {
      Serial.println("Can't send bad request");
    }
  }
  else
  {
    Serial.println("Can't send request");
  }
}

void parseResponse(String responseText)
{
  /*
    Typical response is:
    {"this":"succeeded",
    "by":"getting",
    "the":"dweets",
    "with":[{"thing":"my-thing-name",
      "created":"2016-02-16T05:10:36.589Z",
      "content":{"sensorValue":456}}]}

    You want "content": numberValue
  */
  // now parse the response looking for "content":
  int labelStart = responseText.indexOf("content\":");
  // find the first { after "content":
  int contentStart = responseText.indexOf("{", labelStart);
  // find the following } and get what's between the braces:
  int contentEnd = responseText.indexOf("}", labelStart);
  String content = responseText.substring(contentStart + 1, contentEnd);

  Serial.println(content);

  // now get the value after the colon, and convert to an int:
  int valueStart = content.indexOf(":");
  String valueString = content.substring(valueStart + 1);
  int number = valueString.toInt();

  Serial.print("Value string: ");
  Serial.println(valueString);
  Serial.print("Actual value: ");
  Serial.println(number);
}

void requestCB(void* optParm, AsyncHTTPRequest* request, int readyState)
{
  (void) optParm;

  if (readyState == readyStateDone)
  {
    Serial.println();
    AHTTP_LOGDEBUG(F("**************************************"));
    AHTTP_LOGDEBUG1(F("Response Code = "), request->responseHTTPString());

    if (request->responseHTTPcode() == 200)
    {
      String responseText = request->responseText();

      Serial.println("\n**************************************");
      //Serial.println(request->responseText());
      Serial.println(responseText);
      Serial.println("**************************************");

      parseResponse(responseText);

      request->setDebug(false);
    }
    else
    {
      AHTTP_LOGERROR(F("Response error"));
    }
  }
}

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

  while (!Serial && millis() < 5000);

  Serial.print("\nStart AsyncDweetPOST_STM32 on ");
  Serial.println(BOARD_NAME);
  Serial.println(ASYNC_HTTP_REQUEST_GENERIC_VERSION);

#if defined(ASYNC_HTTP_REQUEST_GENERIC_VERSION_MIN)

  if (ASYNC_HTTP_REQUEST_GENERIC_VERSION_INT < ASYNC_HTTP_REQUEST_GENERIC_VERSION_MIN)
  {
    Serial.print("Warning. Must use this example on Version equal or later than : ");
    Serial.println(ASYNC_HTTP_REQUEST_GENERIC_VERSION_MIN_TARGET);
  }

#endif

  // start the ethernet connection and the server
  // Use random mac
  uint16_t index = millis() % NUMBER_OF_MAC;

  // Use Static IP
  //Ethernet.begin(mac[index], ip);
  // Use DHCP dynamic IP and random mac
  Ethernet.begin(mac[index]);

  Serial.print(F("AsyncHTTPRequest @ IP : "));
  Serial.println(Ethernet.localIP());
  Serial.println();

  request.setDebug(false);

  request.onReadyStateChange(requestCB);
  sendHTTPRequest.start(); //start the ticker.
}

void loop(void)
{
  sendHTTPRequest.update();
}

You are correct that the current implementation in the AsyncDweetPost_STM32.ino example is actually sending a GET request with data in the URL. To send a POST request with data in the body, you can modify the sendRequest function as follows:

void sendRequest(void)
{
  static bool requestOpenResult;

  if (request.readyState() == readyStateUnsent || request.readyState() == readyStateDone)
  {
    String postData = "sensorValue=";
    postData += analogRead(A0);

    Serial.println("\nMaking new POST request");

    requestOpenResult = request.open("POST", "/dweet/for/pinA0-Read");

    if (requestOpenResult)
    {
      request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      request.send(postData);
    }
    else
    {
      Serial.println("Can't send bad request");
    }
  }
  else
  {
    Serial.println("Can't send request");
  }
}

This modification sends a POST request to the server with the data in the postData string as the request body. Note that we also set the "Content-Type" header to "application/x-www-form-urlencoded" to indicate that we are sending data in the request body.

Z

Thanks you.
I need rename request.setRequestHeader because not compile.
According to your suggest itry the code in this way.
The result is that server say "no data received" into the post.
As you see i am working with my notebook acting like server ( and apache, mariadb enabled, working and verified of course)

/****************************************************************************************************************************
  AsyncHTTPRequest_ESP.ino - Dead simple AsyncHTTPRequest for ESP8266, ESP32 and currently STM32 with built-in LAN8742A Ethernet

  For ESP8266, ESP32 and STM32 with built-in LAN8742A Ethernet (Nucleo-144, DISCOVERY, etc)

  AsyncHTTPRequest_Generic is a library for the ESP8266, ESP32 and currently STM32 run built-in Ethernet WebServer

  Based on and modified from asyncHTTPrequest Library (https://github.com/boblemaire/asyncHTTPrequest)

  Built by Khoi Hoang https://github.com/khoih-prog/AsyncHTTPRequest_Generic
  Licensed under MIT license

  Copyright (C) <2018>  <Bob Lemaire, IoTaWatt, Inc.>
  This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License
  as published bythe Free Software Foundation, either version 3 of the License, or (at your option) any later version.
  This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
  You should have received a copy of the GNU General Public License along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *****************************************************************************************************************************/
//************************************************************************************************************
//
// There are scores of ways to use AsyncHTTPRequest.  The important thing to keep in mind is that
// it is asynchronous and just like in JavaScript, everything is event driven.  You will have some
// reason to initiate an asynchronous HTTP request in your program, but then sending the request
// headers and payload, gathering the response headers and any payload, and processing
// of that response, can (and probably should) all be done asynchronously.
//
// In this example, a Ticker function is setup to fire every 300 seconds to initiate a request.
// Everything is handled in AsyncHTTPRequest without blocking.
// The callback onReadyStateChange is made progressively and like most JS scripts, we look for
// readyState == 4 (complete) here.  At that time the response is retrieved and printed.
//
// Note that there is no code in loop().  A code entered into loop would run oblivious to
// the ongoing HTTP requests.  The Ticker could be removed and periodic calls to sendRequest()
// could be made in loop(), resulting in the same asynchronous handling.
//
// For demo purposes, debug is turned on for handling of the first request.  These are the
// events that are being handled in AsyncHTTPRequest.  They all begin with Debug(nnn) where
// nnn is the elapsed time in milliseconds since the transaction was started.
//
//*************************************************************************************************************

#if !( defined(ESP8266) ||  defined(ESP32) )
  #error This code is intended to run on the ESP8266 or ESP32 platform! Please check your Tools->Board setting.
#endif

// Level from 0-4
#define ASYNC_HTTP_DEBUG_PORT     Serial
#define _ASYNC_HTTP_LOGLEVEL_     4

// 300s = 5 minutes to not flooding
#define HTTP_REQUEST_INTERVAL     60  //300

// 10s
#define HEARTBEAT_INTERVAL        10

int status;     // the Wifi radio's status

const char ssid[]        = "DIGIFIBRA-CcNx";
const char password[]    = "bHPbDddeED";

#if (ESP8266)
  #include <ESP8266WiFi.h>
#elif (ESP32)
  #include <WiFi.h>
#endif

#define ASYNC_HTTP_REQUEST_GENERIC_VERSION_MIN_TARGET      "AsyncHTTPRequest_Generic v1.10.2"
#define ASYNC_HTTP_REQUEST_GENERIC_VERSION_MIN             1010002

// Seconds for timeout, default is 3s
#define DEFAULT_RX_TIMEOUT           10

// Uncomment for certain HTTP site to optimize
//#define NOT_SEND_HEADER_AFTER_CONNECTED        true

// To be included only in main(), .ino with setup() to avoid `Multiple Definitions` Linker Error
#include <AsyncHTTPRequest_Generic.h>             // https://github.com/khoih-prog/AsyncHTTPRequest_Generic

#include <Ticker.h>

AsyncHTTPRequest request;
Ticker ticker;
Ticker ticker1;

void heartBeatPrint()
{
  static int num = 1;

  if (WiFi.status() == WL_CONNECTED)
    Serial.print(F("H"));        // H means connected to WiFi
  else
    Serial.print(F("F"));        // F means not connected to WiFi

  if (num == 80)
  {
    Serial.println();
    num = 1;
  }
  else if (num++ % 10 == 0)
  {
    Serial.print(F(" "));
  }
}

void sendRequest()
{
  static bool requestOpenResult;
  char postData[1000]="jdata={post:1}";
  if (request.readyState() == readyStateUnsent || request.readyState() == readyStateDone)
  {
    //requestOpenResult = request.open("GET", "http://worldtimeapi.org/api/timezone/Europe/London.txt");
    //requestOpenResult = request.open("GET", "http://worldtimeapi.org/api/timezone/America/Toronto.txt");
    requestOpenResult = request.open("GET", "http://192.168.1.130/iot_up.php?mac=11:22:33:44:55:66");

    if (requestOpenResult)
    {
      // Only send() if open() returns true, or crash
      //request.send();
      request.setReqHeader("Content-Type", "application/x-www-form-urlencoded");
      Serial.printf("dbg=%s\n",postData);
      request.send(postData);
    }
    else
    {
      Serial.println(F("Can't send bad request"));
    }
  }
  else
  {
    Serial.println(F("Can't send request"));
  }
}

void requestCB(void *optParm, AsyncHTTPRequest *request, int readyState)
{
  (void) optParm;

  if (readyState == readyStateDone)
  {
    AHTTP_LOGDEBUG(F("\n**************************************"));
    AHTTP_LOGDEBUG1(F("Response Code = "), request->responseHTTPString());

    if (request->responseHTTPcode() == 200)
    {
      Serial.println(F("\n**************************************"));
      Serial.println(request->responseText());
      Serial.println(F("**************************************"));
    }
  }
}

void setup()
{
  // put your setup code here, to run once:
  char dot_cnt=0;
  Serial.begin(57600);

  while (!Serial && millis() < 5000);

  Serial.print(F("dbg=Starting AsyncHTTPRequest_ESP using "));
  Serial.println(ARDUINO_BOARD);
  Serial.println(ASYNC_HTTP_REQUEST_GENERIC_VERSION);

  WiFi.mode(WIFI_STA);
  //////////////////////////////
  // Scan
  WiFi.disconnect();
  delay(1000);

    Serial.println();
    Serial.print("Scanning networks ");
    int n = WiFi.scanNetworks();
    Serial.println();
    Serial.print("Done. Printing network list ");
    for (int i = 0; i < n; i++)
    {
        Serial.println(WiFi.SSID(i));
    }

  WiFi.begin(ssid, password);
  WiFi.setAutoReconnect(true);
  //Serial.print(F("dbg=Connecting to WiFi SSID: "));
  //Serial.println(ssid);
  Serial.printf("dbg=Connecting to WiFi SSID:\"%s\":\"%s\"\n",ssid,password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(1000);
    Serial.print(F("."));
    dot_cnt++;
    if(dot_cnt>50){
      Serial.printf("\n");
      dot_cnt=0;
    }
  }

  Serial.print(F("\ndbg=AsyncHTTPRequest @ IP : "));
  Serial.println(WiFi.localIP());

  request.setDebug(false);

  request.onReadyStateChange(requestCB);
  ticker.attach(HTTP_REQUEST_INTERVAL, sendRequest);

  ticker1.attach(HEARTBEAT_INTERVAL, heartBeatPrint);

  // Send first request now
  sendRequest();
}

void loop()
{
}

Finaly works. I forgot modify this line:
requestOpenResult = request.open("POST", "http://192.168.1.130/iot_up.php?mac=11:22:33:44:55:66");

Thanks for all and best regards

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.