Http GET in a loop - only works once

I'm using the following libraries with the following two objects:

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

WiFiClientSecure client;
HTTPClient sender;

Establishing a connection using the following code (works fine):

  // connect to wifi  
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  
  uint8_t i = 0; // temp variable for while loop
  
  while (WiFi.status() != WL_CONNECTED)
  {
      delay(200);
      i++;
      #ifdef DEBUG
      Serial.print(".");
      #endif
      if (i == numOfWIFIConRetries)
      {
        #ifdef DEBUG
        Serial.print(" Failed to connect to WIFI!");
        while(1); // stuck here
        #endif
      }
  }

The function I'm interesting in running several times, gets a char array (as pointer) and send it as a query displays the returned value. This works fine for the first time only. Why is that?

float queryWhatIsTheRate(char* coin)
{
  String payload;
  
  if (sender.begin(client, strcat(coin, "USDT"))))
  {
    if (sender.GET() == HTTP_CODE_OK) 
    {
      payload = sender.getString();
      #ifdef DEBUG
      Serial.println(payload);
      #endif
    }
    else
    {
      #ifdef DEBUG
      //Serial.printf("HTTP-Error: ", sender.errorToString(httpCode).c_str());
      Serial.printf("HTTP-error");
      #endif
    }
  }
  // temp return val
  return 0;
}

So the first time would be a response from the website's API and the rest of the following calls would result in 'HTTP-Error' being printed.

Have you tried calling sender.end() after a HTTP transaction? Maybe that helps.

Since strcat adds USDT to coin, I suspect that the next time you call it, the end of the string will be USDTUSDT, which the API you're calling does not like.

Oops. Good point.

I've tried calling the function 3 times (so not in a loop):

  queryWhatIsTheRate("BTC");
  queryWhatIsTheRate("ETH");  
  queryWhatIsTheRate("DOGE");

And I've added sender.end() before the return. This way the string won't get longer each time. first response is OK. 2nd & 3rd HTTP-error, code 400.

When you call strcat it will add USDT to the string passed. A string like "BTC" occupies four characters. There is no space reserved for the extra letters, but C++ doesn't care. You just wrote on memory that you shouldn't have. Who knows what you overwrote - small wonder that things aren't working as you hoped.

So you suggest taking in the char* as a parameter and concat it with the other char array inside the function into a new char* that will be large enough to host the entire string?

I'm not sure I quite got the specifics there, but yes, you need a buffer with enough space for both strings to be added.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.