【发布时间】:2019-03-09 06:14:23
【问题描述】:
下面的草图在使用 DHCP 时工作正常,但在使用静态 IP 时,HTTPClient.begin() 总是返回连接被拒绝。下面是如何测试这个问题......如果只是这一行:
WiFi.config(local_IP, gateway, subnet);
包含 HTTPClient 将不起作用,但如果注释掉此行,它将连接到服务器并返回字符串就好了。我已经看到这个问题被问了几次,但从来没有得到一个好的答案。有没有办法让 HTTPClient 使用静态 IP?使用带有 DHCP 或固定 IP 的 ESP32 WebServer 库可以正常工作,只有这个 HTTPClient 库不能同时使用固定和 DHCP。无论是在 ESP32 还是 ESP8266 上使用,行为都是相同的。感谢您的帮助。
#include <Arduino.h>
#include <WiFi.h>
#include <WiFiMulti.h>
#include <HTTPClient.h>
#define USE_SERIAL Serial
WiFiMulti wifiMulti;
IPAddress local_IP(192, 168, 1, 111);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
void setup() {
USE_SERIAL.begin(115200);
WiFi.begin("networkSSID", "myPassword");
WiFi.config(local_IP, gateway, subnet);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin("http://www.mocky.io/v2/5c7ddbb13100006c0037600d");
int httpCode = http.GET();
if (httpCode > 0) {
// HTTP header has been send and Server response header has been handled
USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);
if (httpCode == HTTP_CODE_OK) {
String payload = http.getString();
USE_SERIAL.println(payload);
}
} else {
USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}
Serial.println(WiFi.localIP());
delay(5000);
}
【问题讨论】:
标签: c++ arduino httpclient esp8266 esp32