Tutorial – HTTP POST Request dengan ESP8266

Published by faiz on

Sharing is caring!

Berikut ditunjukkan contoh untuk http post request dengan menggunakan NodeMcu (ESP8266) dan Arduino IDE.

#include <ESP8266WiFi.h>

const char* ssid = your wifi ssid;
const char* password = your wifi password;

const char* host =  your hostname;

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

// We start by connecting to a WiFi network

Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}

Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}

void loop() {
delay(5000);
Serial.print("connecting to ");
Serial.println(host);

WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}

String input_data = "";
input_data += "email=faiz.lop@gmail.com&";
input_data += "status=KELUAR&";
input_data += "nama=Faiz";

Serial.print("Requesting POST: ");
// Send request to the server:
client.println("POST /url link HTTP/1.1");
client.println("Host: hostname");
client.println("User-Agent: ESP8266/1.0");
client.println("Connection: close");
client.println("Content-Type: application/x-www-form-urlencoded");
client.print("Content-Length: ");
client.println(input_data.length());
client.println();
client.print(input_data);

unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 5000) {
Serial.println(">>> Client Timeout !");
client.stop();
return;
}
}

// Read all the lines of the reply from server and print them to Serial
while(client.available()){
String line = client.readStringUntil('\r');
Serial.print(line);
}

Serial.println();
Serial.println("closing connection");
}

Sharing is caring!


Tinggalkan Balasan

Alamat e-mel anda tidak akan disiarkan. Medan diperlukan ditanda dengan *