【问题标题】:ESP32 HTTPClient connection refused when using static IP address使用静态 IP 地址时,ESP32 HTTPClient 连接被拒绝
【发布时间】: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


    【解决方案1】:

    我不能 100% 确定(现在无法测试),但这听起来您缺少 DNS 解析。

    试试这个

    ...
    IPAddress local_IP(192, 168, 1, 111);
    IPAddress gateway(192, 168, 1, 1);
    IPAddress subnet(255, 255, 255, 0);
    IPAddress dns(8, 8, 8, 8); // Google DNS
    
    void setup() {
    
      USE_SERIAL.begin(115200);
    
      WiFi.begin("networkSSID", "myPassword");
    
      WiFi.config(local_IP, gateway, subnet, dns);
      ...
    

    【讨论】:

      猜你喜欢
      • 2019-12-11
      • 1970-01-01
      • 2017-01-13
      • 1970-01-01
      • 2013-04-14
      • 2016-04-14
      • 2016-10-18
      • 2015-07-27
      • 2015-02-21
      相关资源
      最近更新 更多