api - 如何使用 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 秒更新一次的替代方案
解决方案
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();
}
}
未经测试,只是输入它,但你明白了。
推荐阅读
- c - 用C计算圆的面积
- javascript - 我的由 makestyle 材质 ui 制作的样式被某些东西覆盖了
- image-processing - cropVariants 的 imageManipulation 中的奇怪行为
- jquery - 使用 jquery 选择多个值
- reactjs - ant-design-pro,登录,TypeError:_form2.default.create(...) 不是函数
- java - while循环的时间复杂度
- python - 当返回一个单词列表并在 Python 中打印时,它只显示列表中第一个单词的字母
- python - 在一组值上集成两个变量的函数
- r - 用于创建分层时间序列的 hts 方法
- python - 生成字典并不总是有效