Skip to content

Instantly share code, notes, and snippets.

@dirkvranckaert
Last active October 21, 2022 09:42
Show Gist options
  • Save dirkvranckaert/93ca29597a9f6732465d23cb9e2b62b3 to your computer and use it in GitHub Desktop.
Save dirkvranckaert/93ca29597a9f6732465d23cb9e2b62b3 to your computer and use it in GitHub Desktop.
#include <ESPAsyncTCP.h> // Manual installation from https://github.com/me-no-dev/ESPAsyncTCP
#include <AsyncHTTPRequest_Generic.h> // Docs available at https://github.com/khoih-prog/AsyncHTTPRequest_Generic
#include <ESP8266WiFi.h>
AsyncHTTPRequest request;
void setup() {
Serial.begin(9600);
WiFi.mode(WIFI_STA);
WiFi.disconnect(true);
WiFi.begin("YOUR_SSID", "YOUR_PASSWORD");
Serial.print("Connecting to wifi...");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(100);
}
Serial.println("");
if (WiFi.status() == WL_CONNECTED) {
Serial.println("Connection OK!!!");
} else {
Serial.println("Connection FAILED!!!");
}
request.setDebug(false);
request.setTimeout(3);
request.onReadyStateChange(handleNetworkResult);
}
void sendRequest()
{
Serial.println("");
Serial.println("");
Serial.println("****************************************");
Serial.println("****************************************");
Serial.println("****************************************");
Serial.println("");
Serial.println("");
static bool requestOpenResult;
if (request.readyState() == readyStateUnsent || request.readyState() == readyStateDone)
{
requestOpenResult = request.open("POST", "http://YOURDOMAIN.eu.ngrok.io/"); // Some accessible POST endpoint over HTTP (no https for testing) that accepts a JSON payload
if (requestOpenResult)
{
String contentType = "application/json";
String userAgent = "MyCustom-User-Agent-V1";
request.setReqHeader("Content-Type", contentType.c_str());
request.setReqHeader("User-Agent", userAgent.c_str());
// Only send() if open() returns true, or crash
Serial.println(F("Sending new request..."));
String content = "{\"field1\": \"BLA\", \"field2\": \"BLA\", \"field3\": \"BLA\"}";
request.send(content);
//request.send("{}"); // Some empty json for testing
}
else
{
Serial.println(F("Can't send bad request"));
}
}
else
{
Serial.println(F("Can't send request"));
}
}
void handleNetworkResult(void *optParm, AsyncHTTPRequest *request, int readyState) {
if (readyState == readyStateDone) {
Serial.println("Network result... ");
Serial.println(request->responseHTTPString());
Serial.println(request->responseHTTPcode());
Serial.println("Network result callback done!");
}
}
void loop() {
sendRequest();
delay(10000); // 10 seconds
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment