I'm calling an api using ESP8266 WiFi Chip. Im declaring a global variable to assign the token sent by the server to it. The variable assignment is made inside a while loop. In this loop i'm reading the contents of the reply "the token" and saving it in the global variable. But when i print out the result outside the while loop to variable is empty. But inside the loop it is not.
After some research i found that the while loop is being executed twice. So once it is putting the token in the global variable and once '0' and i think zero is a null terminator. I tried to add if statements to iterate only once and stuff like that but no use. If anybody could help me with this issue.
Thanks
The Code:
String deviceToken;
WiFiClient client;
if (!client.connect(hostIp, 80)){
Serial.println("Connection to server failed.");
Serial.print(client.connect(hostIp, 80));
return;
}
String authURL = "/api/";
authURL += "startauth/";
authURL += serialValue;
Serial.print("Requesting URL: ");
Serial.println(authURL);
// This will send auth request to the server
client.print(String("GET ") + authURL + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 5000) {
Serial.println(">>> Client Timeout !");
client.stop();
return;
}
}
// Read Auth reply from server and print them to Serial
while(client.available()){
String token = client.readStringUntil('\r');
deviceToken = token;
writeDeviceToken(token.c_str()); //Function to write data in eeprom
Serial.print(deviceToken); //NOT EMPTY
}
Serial.print("Device Token:" + deviceToken); //EMPTY VARIABLE
The response on serial port: