ESP32 Posting Requests to Local Webserver
Code used in this demonstration:
Python Server Code:
# Tinker Foundry Example Python Code
# Python web server to work with ESP32 POST request
# This runs on your local computer, connected on the same WiFi network as your ESP32 controller
from http.server import BaseHTTPRequestHandler, HTTPServer
hostName = "192.168.xx.xxx" # use ipconfig in console (command prompt) to get the "IPv4 Address" of this machine
serverPort = 8080
# BaseHTTPRequestHandler class is used to handle the HTTP requests that arrive at the server
class MyServer(BaseHTTPRequestHandler):
def do_POST(self): # handle POST request from ESP32 (or anything else, really)
content_length = int(self.headers['Content-Length']) # Gets size of data
post_data = self.rfile.read1(content_length) # Gets data
print("Post Data: ")
print(post_data.decode('utf-8')) # This is the message from the POST request
self.send_response(200) # OK HTTP response
self.send_header('Content-type','text/plain')
self.end_headers()
# Do some checks and send response message back to POST requester...
if (post_data.decode('utf-8') == "Tinker Foundry"):
message = "Welcome, great one!"
else:
message = "Access denied, creep!"
self.wfile.write(bytes(message, "utf-8"))
if __name__ == "__main__":
webServer = HTTPServer((hostName, serverPort), MyServer) # HTTPServer
print("Server started http://%s:%s" % (hostName, serverPort))
try:
webServer.serve_forever()
except KeyboardInterrupt:
pass
webServer.server_close()
print("Server stopped.")
ESP32 C-Code for HTTP POST Requests to Server:
// Tinker Foundry
// ESP32 Code for sending a POST request to a local WiFi connected server
// Sends a POST request to server that contains text from Serial input
#include <WiFi.h>
#include <HTTPClient.h>
const char* ssid = "xxxxxxxx"; //input your wifi name
const char* password = "xxxxxxxx"; //input your wifi password
// set up server name with port - don't forgot the trailing forward slash!
const char* server_name = "http://192.168.xx.xxx:8080/";
void setup() {
Serial.begin(115200);
Serial.setDebugOutput(true);
Serial.println();
// Setup WiFi...
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.print("Msg: Ready! Use 'http://");
Serial.print(WiFi.localIP());
Serial.println("' to connect");
}
// Main Loop
void loop() {
delay(500);
Serial.println("Ready for Input.");
// wait for serial input to send out as part of http request
while (Serial.available() == 0){}
String testStr = Serial.readString();
testStr.trim();
if (testStr != "Skip")
{
// check WiFi status
if (WiFi.status() == WL_CONNECTED)
{
HTTPClient http;
http.begin(server_name);
http.addHeader("Content-Type", "text/plain");
// Define data to send with HTTP POST request; in this case, whatever was input on the serial interface
//String httpRequestData = "Input=" + testStr;
String httpRequestData = testStr;
// Send HTTP POST request
int httpResponseCode = http.POST(httpRequestData);
// Check the HTTP Response code
if (httpResponseCode > 0){
Serial.print("Good HTTP response code: ");
} else {
Serial.print("Bad HTTP response code: ");
}
Serial.println(httpResponseCode);
String response = http.getString();
Serial.print("Response: ");
Serial.println(response);
http.end(); // Free up resources
} else {
Serial.println("WiFi Connection Error.");
}
} else
{
Serial.println("Skip");
}
}
Comments
Post a Comment