// https://techtutorialsx.com/2017/05/19/esp32-http-get-requests/
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// ------------- setup ----------------
void setup() {
Serial.begin(115200);
delay(4000);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
Serial.println(WiFi.localIP());
}
// ------------- loop POST ----------------
void loop() {
if(WiFi.status()== WL_CONNECTED){ //Check WiFi connection status
HTTPClient http;
http.begin("http://jsonplaceholder.typicode.com/posts"); //Specify destination for HTTP request
// http.addHeader("Content-Type", "text/plain"); //Specify content-type header
http.addHeader("Content-Type", "application/json");
//int httpResponseCode = http.POST("POSTING from ESP32"); //Send the actual POST request
int httpResponseCode = http.POST("{ \"tag\": 1 }");
if(httpResponseCode>0){
String response = http.getString(); //Get the response to the request
Serial.println(httpResponseCode); //Print return code
Serial.println(response); //Print request answer
}else{
Serial.print("Error on sending POST: ");
Serial.println(httpResponseCode);
}
http.end(); //Free resources
}else{
Serial.println("Error in WiFi connection");
}
delay(10000); //Send a request every 10 seconds
}
/*
// ------------- loop GET ----------------
void loop() {
if ((WiFi.status() == WL_CONNECTED)) { //Check the current connection status
// define a object "http" of class "HTTPClient"
HTTPClient http;
JsonDocument jd;
// char jd_arr[300];
String jd_arr, andBack;
http.begin("http://jsonplaceholder.typicode.com/comments?id=10"); //Specify the URL
// store "error handling number" to variable
int httpCode = http.GET(); //Make the GET request
// Check for the returning code
// >1 = status ok
// <0 = error
// https://github.com/espressif/arduino-esp32/blob/master/libraries/HTTPClient/src/HTTPClient.h#L36 = error codes
if (httpCode > 0) {
String payload = http.getString();
Serial.print("httpCode: "); Serial.println(httpCode); // http error code handling
Serial.println("payload:"); Serial.println(payload); // JSON-string = return text
jd = payload;
serializeJson (jd, jd_arr);
Serial.println("payload of jd_arr:"); Serial.println(jd_arr);
deserializeJson (jd, andBack);
Serial.println(andBack);
}
else {
Serial.println("Error on HTTP request");
}
http.end(); //Free the resources - close the connection - do not forget to do!
}
delay(10000);
}
*/