首页 > 解决方案 > 如何使用 ESP8266 每 1 秒进行一次 API 调用?

问题描述

我尝试向运行 Laravel Api 的本地主机发出 HTTP 请求。

 if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    http.begin(url + "update");      //request destination
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");  //content-type header

    String stringData = "payload=" + data;
    int httpCode = http.POST(stringData);
    String payload = http.getString();
    Serial.print(httpCode);
    http.end();
  }
 delay(2000);
}

当我减少延迟值 <= 2000 时,nodeMCU 未按预期执行。测试时出现 429 错误建议使用可以每 1 秒更新一次的替代方案

标签: apiresthttpesp8266arduino-esp8266

解决方案


429 Too Many Requests“表示用户在给定时间内发送了太多请求”。服务器可能很慢,或速率受限

服务器可能会发送一个Retry-After标头;如果是这样,它会告诉您在发出新请求之前必须等待多长时间。

我怀疑您必须在服务器端进行更改以使其尽可能快;我怀疑 ESP8266 是罪魁祸首。

请注意,如果处理请求的时间超过 1 秒,那么无论如何你都不走运。

顺便说一句,你能试试这个,看看它是否有效?只是为了排除一些其他潜在的问题。它消除了低效delay(),只做HTTPClient http;一次。

HTTPClient http;
unsigned long int lastPost = 0;
int postInterval = 1000; // Post every second

void setup() {
  // Setup stuffs
}

void loop() {
  if (WiFi.status() == WL_CONNECTED && (millis() - lastPost) >= postInterval) {
    http.begin(url + "update"); //request destination
    http.addHeader("Content-Type", "application/x-www-form-urlencoded"); //content-type header
    String stringData = "payload=" + data;
    int httpCode = http.POST(stringData);
    String payload = http.getString();
    Serial.print(httpCode);
    http.end();

    lastPost = millis();
  }
}

未经测试,只是输入它,但你明白了。


推荐阅读