I’m trying to do a http request with my esp8266 and I get the Response code 400 from my ESP. Do you have an idea what is wrong with my code?
I used the Code from this Webside:
https://randomnerdtutorials.com/esp32-esp8266-mysql-database-php/
The Website is hosted by Strato
C code:
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
const char* ssid = "----";
const char* password = "----";
const char* serverName = "----";
String apiKeyValue = "tPmAT5Ab3j7F9";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while(WiFi.status() != WL_CONNECTED) {
delay(500);
}
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());
}
void loop() {
if(WiFi.status()== WL_CONNECTED){
WiFiClient client;
HTTPClient http;
http.begin(client, serverName);
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
String httpRequestData = "api_key=" + apiKeyValue
+ "&sensor=" + '1'
+ "&location=" + '2'
+ "&value1=" + '3'
+ "&value2=" + '4' + "";
Serial.println(httpRequestData);
int httpResponseCode = http.POST(httpRequestData);
if (httpResponseCode>0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
http.end();
}
else {
}
delay(10000);
}
PHP code:
$servername = '----';
$dbname = '----';
$username = '----';
$password = '----';
$Zeit = 'date("YmdHis")';
$api_key_value = "tPmAT5Ab3j7F9";
$api_key= $sensor = $location = $value1 = $value2 = $value3 = "";
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$api_key = test_input($_POST["api_key"]);
if($api_key == $api_key_value) {
$sensor = test_input($_POST["sensor"]);
$location = test_input($_POST["location"]);
$value1 = test_input($_POST["value1"]);
$value2 = test_input($_POST["value2"]);
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO geraet_1 (sensor,Ort,Temperatur,Luftfeuchtigkeit,Zeit)
VALUES (
'" . $sensor . "',
'" . $location . "',
'" . $value1 . "',
'" . $value2 . "',
'" . $Zeit . "')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
else {
echo "Wrong API Key provided.";
}
}
else {
echo "No data posted with HTTP POST.";
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
and here is the output from my esp:
HTTP Response code: 400
api_key=tPmAT5Ab3j7F9&sensor=1&location=1&value1=2&value2=5