如何使用 ESP8266 使 API 每 1 秒调用一次?

How to make API Call every 1second using ESP8266?

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

 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 秒更新一次

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();
  }
}

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