/*
ESP32 HTTPClient JSON Example
*/
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
// Wifi Login
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// Server IP Endpoint
const String url = "http://47.7.63.215:8089/data";
void getJSON() {
// Create HTTP Request
HTTPClient http;
http.useHTTP10(true);
http.begin(url);
// Send HTTP GET
Serial.printf("Http Code %d\n", http.GET());
String result = http.getString();
// Fill JSON Object
DynamicJsonDocument doc(4096);
DeserializationError error = deserializeJson(doc, result);
// Test if parsing succeeds.
if (error) {
Serial.print("deserializeJson() failed: ");
Serial.println(error.c_str());
return;
}
// Read Values and Print
String age = doc["age"].as<String>();
String city = doc["city"].as<String>();
String name = doc["name"].as<String>();
Serial.printf("Name: %12s, City: %12s, Age: %12s\n", name, city, age);
http.end();
}
void postJSON() {
// Create Request
HTTPClient http;
http.useHTTP10(true);
http.begin(url);
http.addHeader("Content-Type", "application/json");
// Create JSON Data Packet
DynamicJsonDocument doc(4096);
String resp_str;
doc["age"] = 123;
doc["city"] = "Haha";
doc["name"] = "CEEE";
serializeJson(doc, resp_str);
// POST data to server
int httpResponseCode = http.POST(resp_str);
http.end();
}
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password, 6);
Serial.println("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.print("\nOK! IP=");
Serial.println(WiFi.localIP());
}
void loop() {
getJSON();
postJSON();
getJSON();
while (1)
{
}
}