wdbwdb1
wdbwdb1

Reputation: 225

ESP32 HTTPClient connection refused when using static IP address

The below sketch works fine when using DHCP but when using static IP, HTTPClient.begin() always returns connection refused. Here is how to test this problem... If simply the line:

WiFi.config(local_IP, gateway, subnet);

is included HTTPClient will not work, but if this line is commented out it will connect to server and return the string just fine. I've seen this question asked a few times but never got a good answer. Is there a way to get HTTPClient to work with static IP? Using the ESP32 WebServer library with DHCP or fixed IP works just fine, only this HTTPClient library isn't working with both fixed and DHCP. The behavior is the same whether used on ESP32 or ESP8266. Thanks for any help.

#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);

}

Upvotes: 1

Views: 3510

Answers (1)

Marcel St&#246;r
Marcel St&#246;r

Reputation: 23525

I can't be 100% sure (can't test right now) but this sounds like you're missing the DNS resolution.

Try this

...
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);
  ...

Upvotes: 1

Related Questions