ESP8266 POST请求返回301错误码,如何解决?
解决ESP8266 POST请求返回301错误的方案
301错误是永久重定向,结合Hostinger的环境,核心原因是Hostinger默认强制HTTPS跳转,你用http://发起的请求会被自动重定向到https://版本;另外部分域名还存在带www/不带www的重定向差异。以下是具体解决步骤:
1. 确认重定向目标
用浏览器访问你的PHP文件地址http://MY_WEBSSITE/post-esp-data.php,观察地址栏最终跳转后的URL,比如是否变成https://MY_WEBSSITE/post-esp-data.php或https://www.MY_WEBSSITE/post-esp-data.php,后续代码里的serverName要直接使用这个最终HTTPS地址。
2. 修改ESP8266代码适配HTTPS和重定向
由于HTTPS需要SSL加密,需替换普通WiFiClient为WiFiClientSecure,同时正确开启重定向跟随:
#include <WiFiClientSecure.h> const char* ssid = "MY_NETWORK"; const char* password = "MY_PASS"; // 替换为浏览器跳转后的HTTPS地址 const char* serverName = "https://MY_WEBSSITE/post-esp-data.php"; String apiKeyValue = "MY_API_KEY"; WiFiClientSecure wifiClient; void setup() { Serial.begin(115200); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("\nWiFi connected"); // 测试阶段可跳过证书验证(生产环境建议添加证书指纹) wifiClient.setInsecure(); } void loop() { if(WiFi.status() == WL_CONNECTED) { HTTPClient http; // 强制跟随POST请求的重定向(默认仅跟随GET) http.setFollowRedirects(HTTPC_FORCE_FOLLOW_REDIRECTS); http.begin(wifiClient, serverName); http.addHeader("Content-Type", "application/x-www-form-urlencoded"); // 补充你的实际数据字段 String httpRequestData = "api_key=" + apiKeyValue + "&temperature=25&humidity=60"; int httpResponseCode = http.POST(httpRequestData); Serial.print("httpResponseCode: "); Serial.println(httpResponseCode); // 打印响应内容,方便调试PHP端问题 if(httpResponseCode > 0) { String response = http.getString(); Serial.println("Response: " + response); } http.end(); } delay(5000); // 避免频繁请求服务器 }
3. 额外排查点
- 确保PHP文件放在Hostinger的
public_html目录下,文件权限设置为644 - 检查PHP代码中是否正确处理了POST参数,比如是否读取了
$_POST['api_key']等字段 - 生产环境使用时,建议去掉
wifiClient.setInsecure(),添加对应域名的SSL证书指纹,避免安全风险
内容的提问来源于stack exchange,提问作者Black X-Treme
相关产品推荐
相关产品推荐

