¡Tu carrito está actualmente vacío!
ESP8266 NodeMCU HTTP GET y HTTP POST (JSON, codificación de URL, texto)

El ESP8266 NodeMCU es una plataforma de desarrollo basada en el chip ESP8266, que permite la conexión a redes Wi-Fi y es muy utilizada para proyectos de Internet de las cosas (IoT).
HTTP GET y POST. A continuación, ejemplos para ambas operaciones, incluyendo manejo de JSON y codificación de URL:
1. HTTP GET con ESP8266 NodeMCU:
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
const char *ssid = "nombre_de_tu_wifi";
const char *password = "contraseña_de_tu_wifi";
const char *url = "http://ejemplo.com/api/data"; // Cambia esto por tu URL
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Conectando a WiFi...");
}
Serial.println("Conectado a WiFi");
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
Serial.print("Realizando GET a: ");
Serial.println(url);
http.begin(url);
int httpCode = http.GET();
if (httpCode > 0) {
String payload = http.getString();
Serial.println("Respuesta del servidor:");
Serial.println(payload);
} else {
Serial.print("Error en la conexión. Código de error: ");
Serial.println(httpCode);
}
http.end();
}
delay(5000); // Espera 5 segundos antes de realizar la siguiente solicitud
}
2. HTTP POST con ESP8266 NodeMCU (enviando JSON):
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
const char *ssid = "nombre_de_tu_wifi";
const char *password = "contraseña_de_tu_wifi";
const char *url = "http://ejemplo.com/api/data"; // Cambia esto por tu URL
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Conectando a WiFi...");
}
Serial.println("Conectado a WiFi");
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
Serial.print("Realizando POST a: ");
Serial.println(url);
http.begin(url);
http.addHeader("Content-Type", "application/json");
// Construye el objeto JSON
String jsonPayload = "{\"sensor\": \"temperatura\",\"value\": 25.5}";
int httpCode = http.POST(jsonPayload);
if (httpCode > 0) {
String payload = http.getString();
Serial.println("Respuesta del servidor:");
Serial.println(payload);
} else {
Serial.print("Error en la conexión. Código de error: ");
Serial.println(httpCode);
}
http.end();
}
delay(5000); // Espera 5 segundos antes de realizar la siguiente solicitud
}
Se deben cambiar nombre_de_tu_wifi
y contraseña_de_tu_wifi
con los detalles de tu red Wi-Fi, y http://ejemplo.com/api/data
con la URL a la que deseas hacer la solicitud. Además, puedes ajustar el contenido del JSON según tus necesidades en el ejemplo de POST.
Etiquetas:
Deja una respuesta