ESP32 HTTP Client - HTTP.BEGIN - connection refused

I am new to ESP32. However, I had worked a little with ESP8266.
I am using HTTPClient.h library to make GET request to API.
I am using the BASICHTTPCLIENT example and modified a little to suit my needs.
When I try http.begin - it works as long as I restart the ESP32-WROOM device. However, if I leave this for few minutes and then attempt the http.begin requests, it returns with -1 HTTP Code and the message I get is Connection Refused.
See the entire code below:-

/**
 * BasicHTTPClient.ino
 *
 *  Created on: 24.05.2015
 *
 */

#include <Arduino.h>

#include <WiFi.h>
#include <WiFiMulti.h>
#include <WiFiClientSecure.h>
#include <WiFiClient.h>
#include "string.h"

#include <HTTPClient.h>


#define USE_SERIAL Serial


 

WiFiMulti wifiMulti;
String HOST_NAME;
WiFiClientSecure  Secure_Client;
WiFiClient Client;
String  StringData;
String  LOGIC_STRING;
int   httpCode;
String payload;
int   FIRST_TIME;








void setup() {

  USE_SERIAL.begin(115200);

  USE_SERIAL.println();
  USE_SERIAL.println();
  USE_SERIAL.println();

  for (uint8_t t = 4; t > 0; t--) {
    USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
    USE_SERIAL.flush();
    delay(1000);
  }

  wifiMulti.addAP("my ssid", "my pw");
  
}

void loop() 
{
  // wait for WiFi connection
  if ((wifiMulti.run() == WL_CONNECTED)) 
  {

    HTTPClient http;

    
          if (wifiMulti.run() != WL_CONNECTED)
          {
              FIRST_TIME = 100; // If Wifi is disconnected somehow then come out

          }


      }
        

    }


    if (Serial.available ())
    {
      StringData = Serial.readString();
      Serial.println (StringData);

      if (StringData == "WiFi Status?")
      {
        if (wifiMulti.run() == WL_CONNECTED)
        {
          Serial.println ("Yes");
        }
        else
        {
          Serial.println ("No");
        }

      }

      else if (StringData == "SSID?")
      {
          Serial.println (WiFi.SSID ());
          

      }

      else if (StringData == "IP Address?")
      {
          Serial.println (WiFi.localIP());

      }

      else if (StringData == "Mode?")
      {
          Serial.println (WiFi.getMode());

      }
      
      
      else if (StringData.startsWith("RAW="))
      {

                
            
                LOGIC_STRING = StringData.substring(4,StringData.length());
                
               
                USE_SERIAL.print ("Attempting Complete String Input \n");
                Serial.println(LOGIC_STRING);
                http.begin(LOGIC_STRING); //- This Does not work

                USE_SERIAL.print("[HTTP] GET...\n");
                // start connection and send HTTP header
                httpCode = http.GET();

                // httpCode will be negative on error
                if (httpCode > 0) 
                {
                  // HTTP header has been send and Server response header has been handled
                  USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);

                  // file found at server
                  if (httpCode == HTTP_CODE_OK) 
                  {
                      payload = http.getString();
                      USE_SERIAL.println(payload);
                  }
                } 
                else 
                {


                    USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
                    
                }

                http.end();



      }
      
      
    


    }


  }

}

Looking forward to hear from someone.

the code you posted likely does not compile (indent the code and you'll see you have code outside functions)

That Must be my copying error:-


/**
 * BasicHTTPClient.ino
 *
 *  Created on: 24.05.2015
 *
 */

#include <Arduino.h>

#include <WiFi.h>
#include <WiFiMulti.h>
#include <WiFiClientSecure.h>
#include <WiFiClient.h>
#include "string.h"

#include <HTTPClient.h>


#define USE_SERIAL Serial

 

WiFiMulti wifiMulti;
String HOST_NAME;
WiFiClientSecure  Secure_Client;
WiFiClient Client;
String  StringData;
String  LOGIC_STRING;
int   httpCode;
String payload;
int   FIRST_TIME;





void setup() {

  USE_SERIAL.begin(115200);

  USE_SERIAL.println();
  USE_SERIAL.println();
  USE_SERIAL.println();

  for (uint8_t t = 4; t > 0; t--) {
    USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
    USE_SERIAL.flush();
    delay(1000);
  }

  wifiMulti.addAP("my ssid", "my pw");
  FIRST_TIME = 0;
}

void loop() 
{
  // wait for WiFi connection
  if ((wifiMulti.run() == WL_CONNECTED)) 
  {

    HTTPClient http;

    


    if (Serial.available ())
    {
      StringData = Serial.readString();
      Serial.println (StringData);

      if (StringData == "WiFi Status?")
      {
        if (wifiMulti.run() == WL_CONNECTED)
        {
          Serial.println ("Yes");
        }
        else
        {
          Serial.println ("No");
        }

      }

      else if (StringData == "SSID?")
      {
          Serial.println (WiFi.SSID ());
          

      }

      else if (StringData == "IP Address?")
      {
          Serial.println (WiFi.localIP());

      }

      else if (StringData == "Mode?")
      {
          Serial.println (WiFi.getMode());

      }
      

      else if (StringData.startsWith("RAW="))
      {

                
            
                LOGIC_STRING = StringData.substring(4,StringData.length());
                
               
                USE_SERIAL.print ("Attempting Complete String Input \n");
                Serial.println(LOGIC_STRING);
                http.begin(LOGIC_STRING); //- This Does not work

                USE_SERIAL.print("[HTTP] GET...\n");
                // start connection and send HTTP header
                httpCode = http.GET();

                // httpCode will be negative on error
                if (httpCode > 0) 
                {
                  // HTTP header has been send and Server response header has been handled
                  USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);

                  // file found at server
                  if (httpCode == HTTP_CODE_OK) 
                  {
                      payload = http.getString();
                      USE_SERIAL.println(payload);
                  }
                } 
                else 
                {


                    USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
                    
                }

                http.end();


           

      }

      
    


    }


  }

}

Are you using IDE v2.x? After a successful compile/Verify, if you hover the mouse over

#include <HTTPClient.h>

you should get a tooltip with the full path to this file. It likely has arduino15 somewhere near the beginning. It should also have a version number near the middle, 2. something or 3. something.

Version 3.0.0 was released a few days ago, and apparently has some problems reusing connections.

One thing to try regardless of the version is

    HTTPClient http;
    http.setReuse(false);  // add this

It is Version 3.0.0 when I hover the mouse the library folder is esp32 followed by Version 3.0.0.

IDE is Version 2.3.2

Apologies in advance but what does http.setReuse(false); do? and do I need to add this line before http.begin?

HTTP 1.1, which is the most common, tries to reuse a connection, because it takes time and effort to set them up and tear them down. But these reused connections seem to have a problem with v3.0.0, so setReuse(false) will revert to closing connections after use, as was normally done with HTTP 1.0. Then it should try to create a new one every time, which might work more reliably. This is just a workaround.

Put it right after declaring the HTTPClient, as shown.

Another thing to try is to revert your Board library to the latest version 2 available.

I have tried placing set Reuse (false) but after about half an hour of not doing anything and then using http.begin and it still does not work.

How can i go back to version 2.0.0 of HTTPclient library?

you have this test

if it fails for whatever reason you won't know it and the loop() will just do nothing.

āžœ add an error message if the condition is false

It is connected to Wifi because when I send something on Serial Terminal, I get below response:-

[HTTP] GET...

[HTTP] GET... failed, error: connection refused

I can only get above if it is in the LOOP. Also I get responses with SSID? command as used in my code.

do you have a way to see if the request made it to the web server ?

Yes. But the request is not getting there.
I have tried different APIs. in fact the code works absolutely fine, if I restart the module. It is after a little while, it starts giving this error.

what does this print ?

This print the string what I key in from my computer. i.e. the API URL. This way I know that that the code is being executed and with same code, I can try various APIs.

So for example, I want to see get response from http://testapi.com/get, i would send RAW=http://testapi.com/get. The code then will take http://testapi.com/get into LOGIC_STRING variable, print the LOGIC_STRING variable, so that I can confirm, it has got the right data or not, and then execute http.begin.

can you try with adding one line (just to make sure there are no invisible character in the string)

      else if (StringData.startsWith("RAW="))  {
                LOGIC_STRING = StringData.substring(4,StringData.length());
                LOGIC_STRING.trim();  // <==== ADD THIS LINE
                USE_SERIAL.print ("Attempting Complete String Input \n");

It may not be just that, but some other related one (or more than one). You can easily revert to an earlier version of all the board's libraries and tools.

Open the Boards manager: 2nd icon down the left edge. Find your board: type in the (partial) name of your board to search. It should say "3.0.0 installed" in small text, and "REMOVE" to the right of the "3.0.0" in the select/dropdown. Click there and pick the latest 2.x.x, and click the now-"INSTALL" button.

I have changed the version back to 2.0.17 and it started working properly.

This clearly indicates that the issues are with the Library.

Hopefully new version will be released soon.

Thank you for your help.

There was not issue with characters as I printed all the characters. The fact that it worked in the beginning and stopped working after a while re-emphasise this.

I have rolled back the library for board from 3.0.0 to 2.0.17 and it started working correctly.

I did not make any change to the code.

Thank you for your help.

You are an absolute G.

I've been deep into a project that is nearly complete and made the mistake of letting the annoying 'Update libraries' popup finally get the best of me. That was a few days ago and have been scratching my head wondering what's been going on since then.

This is absolutely the solution to this issue.