As I wrote here before, the ESP8266 is one of the best controllers for simple tasks. It’s cheap, reliable, and easy to code with Arduino.
Sometimes, even great things as this chip can cause a bit of a headache, like this time around, when I got “connection refused” error when I tried to open an HTTP connection to one of my services.
Mind you, connecting ESP8266, and getting data from the Internet is something that I’ve done many times, on every project I did. I got this error for the first time on the last project I’ve done (opening the gate for the garage automatically when I get home – if you want to hear more about it let me know in the comments below) using the ESP8266.
Let’s list the most common causes for this error:
Causes for HTTP connection refused on ESP8266 with Arduino
- The chip is not connected to an AP when the request is made. Maybe this is obvious, but make sure you only call HTTP requests after the controller is connected and got an IP. You can read my post on best practices to how to connect an ESP8266 to WiFi AP
- Make sure the address you are trying to reach is accessible to the controller.
- Avoid using a localhost address.
- Check that you can reach the endpoint from another device, preferably on the same network.
- Make sure that the response from the remote server is received within 2-3 seconds. Even though it can cause another error, it might also manifest itself as a connection refused error.
- Make sure you make the HTTP request from the main loop of the code. Of course, you can still use functions to connect, but it still has to be called as a directive of the main loop. Asynchronous functions of the connection events will always issue this error. I discovered that while trying to initiate a connection on the onStationModeGotIP event of the WiFi connection process. Even though the chip was connected to the internet, was recognized by the router, and answered ping requests, it still refused to connect on this event. After a bit of trial and error, I witnessed this behavior on other asynchronous events, but not all, so if you just can figure out why the connection isn’t working, this just might be it.
I hope this tip helped!