我希望我的 ESP32 通过 HTTP POST 请求将数据写入我的本地数据库。 为此,我下载了 XAMPP 并编写了一个将数据插入数据库的 PHP 脚本。 此外,我有连接到 WiFi 的 ESP32 代码,应该通过将数据发送到 PHP 脚本来发送 HTTP POST 请求。 每次尝试将请求发送到本地 PHP 脚本时,我都会遇到错误代码 -1。 但是,当我将请求发送到例如 http://arduinojson.org/example.json 时,httpResponseCode 不等于 -1(httpResponseCode = 403 -> 禁止访问)。
ESP32代码:
#include <WiFi.h>
#include <HTTPClient.h>
#include <Wire.h>
//network credentials
const char* ssid = "[My_WIFI_SSID]";
const char* password = "[My_WIFI_PASSWORD]";
//Domain name and URL path or IP address with path
const char* serverName = "http://[My_IP_ADDRESS]/insert_temp-post.php";
//using http://arduinojson.org/example.json instead -> httpResponseCode != -1
// Keep this API Key value to be compatible with the PHP code provided in the project page.
// If you change the apiKeyValue value, the PHP file also needs to have the same key
String apiKeyValue = "tPmAT5Ab3j7F9";
void setup() {
Serial.begin(9600);
WiFi.begin(ssid, password);
Serial.println("Connecting");
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());
}
void loop() {
//Check WiFi connection status
if(WiFi.status()== WL_CONNECTED){
WiFiClient client;
HTTPClient http;
// Domain name with URL path or IP address with path
http.begin(client, serverName);
//content-type header specification
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
// Prepare HTTP POST request data
String httpRequestData = "api_key=" + apiKeyValue + "&temperature=34.5";
Serial.print("httpRequestData: ");
Serial.println(httpRequestData);
// Send HTTP POST request
int httpResponseCode = http.POST(httpRequestData);
if (httpResponseCode>0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
// Free resources
http.end();
}
else {
Serial.println("WiFi Disconnected");
}
//Send an HTTP POST request every 30 seconds
delay(30000);
}
您知道什么可能导致此错误代码吗? 直到现在我才发现您应该在服务器 URL 中使用您的 PC IP 地址而不是“localhost”。我希望它能解决我的问题,但显然这不是我的正确解决方案。