Problem with esp8266 GET request throws http error -1

I get an http error -1 on esp8266 with the following code. Connection to Wifi is working fine. but http request leads to an erorr. I tried with GET and POST as well but same error. http request works well in the browser on the other hand.

Can you please help to analyze this issue?

#include <ESP8266WiFi.h>
//#include <WiFiClientSecure.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#include <UrlEncode.h>


const char* ssid = "XXXXX";
const char* password = "XXXXXX";

// +international_country_code + phone number
String phoneNumber = "XXXXXXXXXXXXX";
String apiKey = "XXXXXXX";

void sendMessage(String message){

  // Data to send with HTTP POST
   String GetRequest = "http://api.callmebot.com/whatsapp.php?phone=XXXXXXXXXXXX&text=Hurra%3A%20Hello%20from%20ESP8266%21&apikey=XXXX8";
  WiFiClient client;    
  HTTPClient http;
  http.begin(client, GetRequest);

  // Specify content-type header
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");
  
  // Send HTTP POST request
  int httpResponseCode = http.GET();
  if (httpResponseCode == 200){
    Serial.print("Message sent successfully");
  }
  else{
    Serial.println("Error sending the message");
    Serial.print(url);
    Serial.println(httpReqestData );
    Serial.print("HTTP response code: ");
    Serial.println(httpResponseCode);
  }

  // Free resources
  http.end();
}

void setup() {
  Serial.begin(115200);

  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());

  // Send Message to WhatsAPP
  sendMessage("Hurra: Hello from ESP8266!");
}

void loop() {
  
}

Post the full error.

Does the "-1" get printed inside the http.GET() call, or after the return? Have you tried httpResponseCode > 0 to view the return code?

Hi xfpd, Thanks dear for your response :slightly_smiling_face:.

If you see the source code above, HTTP response code: -1 is the the http code which i get back from http.GET() call. How can i get more error information? Is there any API to do this?

In addition, i noticed that the API http.begin(client, GetRequest) now expects two input parameters, WifiClient and URL. Old version of this API http.begin() only had one parameter which was the URL.

First of all, if instead of a genuine HTTP status code in the range [100,600), you get -1, that means

#define HTTPC_ERROR_CONNECTION_FAILED   (-1)

which also includes

constexpr int HTTPC_ERROR_CONNECTION_REFUSED __attribute__((deprecated)) = HTTPC_ERROR_CONNECTION_FAILED;

meaning you didn't even connect to the server.

Your best bet might be to enable debug output, like these

    if (err == ERR_OK) {
        DEBUG_WIFI_GENERIC("[hostByName] Host: %s IP: %s\n", aHostname, aResult.toString().c_str());
        return 1;
    }

    DEBUG_WIFI_GENERIC("[hostByName] Host: %s lookup error: %s (%d)!\n",
            aHostname,
            (err == ERR_TIMEOUT) ? "Timeout" :
            (err == ERR_INPROGRESS) ? "No response" :
                "Unknown", static_cast<int>(err));

    return 0;

Notice there are messages for both progress and failure; in this case, whether the host name lookup worked. That is defined for the WiFiClient as

#ifdef DEBUG_ESP_WIFI
#ifdef DEBUG_ESP_PORT
#define DEBUG_WIFI_GENERIC(fmt, ...) DEBUG_ESP_PORT.printf_P( (PGM_P)PSTR(fmt), ##__VA_ARGS__ )
#endif
#endif

Similarly, for the HTTPClient, there's also

#ifdef DEBUG_ESP_HTTP_CLIENT
#ifdef DEBUG_ESP_PORT
#define DEBUG_HTTPCLIENT(fmt, ...) DEBUG_ESP_PORT.printf_P( (PGM_P)PSTR(fmt), ## __VA_ARGS__ )
#endif
#endif

So you need to define three things. Luckily, these are available in the bottom half of the IDE's Tools menu, in the board-specific settings. First, set Debug port to Serial (or Serial1, as appropriate) to actually see the output. Then for Debug Level there are a few choices that have both of the other two flags. The shortest to type here is SSL+TLS_MEM+HTTP_CLIENT+HTTP_SERVER+CORE+WIFI+HTTP_UPDATE+UPDATER+OTA+OOM+MDNS right near the bottom.

Re-Upload to rebuild and try again.

Thanks kenb4 for your response.

I switched on the debug with the max debug level. I could see the following output:

SDK:2.2.2-dev(38a443e)/Core:3.1.2=30102000/lwIP:STABLE-2_1_3_RELEASE/glue:1.2-65-g06164fb/BearSSL:b024386
fpm close 1
mode : sta(c4:d8:d5:01:08:51)
add if0
Connecting
.....scandone
state: 0 -> 2 (b0)
.state: 2 -> 3 (0)
state: 3 -> 5 (10)
add 0
aid 4
cnt

connected with TP-Link_F6C9, channel 4
dhcp client start...
.ip:192.169.1.107,mask:255.255.255.0,gw:192.169.1.1

Connected to WiFi network with IP Address: 192.169.1.107
clientStatus: 0
BeginCheck: 1
HTTP response code: -1

pm open,type:2 0

I still could not more information about the http error.

Thank in advance for your help.

Which level is that? What board are you using?

Did you also enable the Debug port? You can check this in your sketch

#ifdef DEBUG_ESP_PORT
  Serial.println("debug port enabled");
  Serial.println(sizeof(DEBUG_ESP_PORT));
#endif

Thanks buddy again for your effort. I use ESP8266 12E NodeMcu board.

Yes, Debug Port: Serial is enabled.

Serial.println("debug port enabled");
Serial.println(sizeof(DEBUG_ESP_PORT));

gives me the following output:
debug port enabled
32

I use the following debug level as suggested by you: SSL+TLS_MEM+HTTP_CLIENT+HTTP_SERVER+CORE+WIFI+HTTP_UPDATE+UPDATER+OTA+OOM+MDNS

I see the following messages (lookup error) in debug mode when i try to connect to an URL like google.de:

[HTTP-Client][begin] url: http://google.de
[HTTP-Client][begin] host: google.de port: 80 url:
[HTTP-Client][sendRequest] type: 'GET' redirCount: 0
[hostByName] request IP for: google.de
[hostByName] Host: google.de lookup error: Timeout (-3)!
[HTTP-Client] failed connect to google.de:80
[HTTP-Client][returnError] error(-1): connection failed
HTTP response code: -1

Watching the output, is there any delay between these two lines? Does it actually time out? This is actually on the WiFiClient, and defaults to

WiFiClient::WiFiClient()
: _client(0), _owned(0)
{
    _timeout = 5000;
    WiFiClient::_add(this);
}

WiFiClient::WiFiClient(ClientContext* client)
: _client(client), _owned(0)
{
    _timeout = 5000;

5 seconds. You could try increasing it

  WiFiClient wifi;
  wifi.setTimeout(15000);
  HTTPClient http;

Hi Kenb4, i tried your tip, but unfortunately it does not help. I get the same error as seen below.
<
SDK:2.2.2-dev(38a443e)/Core:3.1.2=30102000/lwIP:STABLE-2_1_3_RELEASE/glue:1.2-65-g06164fb/BearSSL:b024386
fpm close 1
mode : sta(c4:d8:d5:01:08:51)
add if0
wifi evt: 8
Connecting
wifi evt: 2
.....scandone
state: 0 -> 2 (b0)
.state: 2 -> 3 (0)
state: 3 -> 5 (10)
add 0
aid 2
cnt

connected with TP-Link_F6C9, channel 4
dhcp client start...
wifi evt: 0
.ip:192.168.1.106,mask:255.255.255.0,gw:192.168.1.1
wifi evt: 3
.
Connected to WiFi network with IP Address: 192.168.1.106
clientStatus: 0
[HTTP-Client][begin] url: http://google.de
[HTTP-Client][begin] host: google.de port: 80 url:
BeginCheck: 1
[HTTP-Client][sendRequest] type: 'GET' redirCount: 0
[hostByName] request IP for: google.de
[hostByName] Host: google.de lookup error: Timeout (-3)!
[HTTP-Client] failed connect to google.de:80
[HTTP-Client][returnError] error(-1): connection failed
HTTP response code: -1
debug port enabled
32
[HTTP-Client][end] tcp is closed
[HTTP-Client][end] tcp is closed
pm open,type:2 0
<