I made a little function to get some values from an API. It returns a 0 or 1 based on success of failure (like a pro!). It’s based on the ESP board (Wemos) board, so I’m not really sure how to make it for Ethernet, but the principle will be the same I think. The function below also does a little parsing, but you can probably figure that out ;). It fills a variable (array) with each line of text retrieved from the URL/textfile/callback/however you want to call it.
char server[] = "api.sunrise-sunset.org";
WiFiClient client;
bool getrawdata()
{
if(debug) { Serial.println("Disconnecting Blynk"); }
Blynk.disconnect(); // Disconnect Blynk, cause API call has to be made
// Put current date in for retrieving correct date
char currentDateBuffer[12];
sprintf(currentDateBuffer,"%04u-%02u-%02u ", year(currentTime), month(currentTime), day(currentTime) );
delay(750);
// Make request http://api.sunrise-sunset.org/json?lat=36.7201600&lng=-4.4203400&date=2016-08-25 (with variable data of course)
if (client.connect(server, 80))
{
if(debug) { Serial.println("Connecting to server ..."); }
client.print("GET /json?lat=53.097001&lng=6.054036&date=");
client.print(currentDateBuffer);
client.println(" HTTP/1.1");
client.println("Host: api.sunrise-sunset.org");
client.println("Accept: text/html");
client.println("Connection: close");
client.println();
if(debug) { Serial.println("Connected to server"); }
delay(750);
// Read all characters into one big, noisy array full of stuff (contents[])
if(debug) { Serial.println("Now reading data into temp var"); }
int i=0;
String contents[15];
String inputString = "";
inputString.reserve(200);
while (client.available())
{
char c = client.read();
inputString += c;
if (c == '\n')
{
inputString.trim(); // Remove dumbass whitespaces and too much CR, LF etc.
if(debug) { Serial.print(i); }
if(debug) { Serial.print(": Received non-useless data, processing: "); }
if(debug) { Serial.println(inputString); }
contents[i] = inputString;
inputString = "";
i++;
}
}
if(contents[0] == "HTTP/1.1 200 OK")
{
if(debug) { Serial.println(contents[0]); }
if(debug) { Serial.println("Stopping client"); }
client.stop();
// Result set to this var
useFullData = contents[11];
if(debug) { Serial.println("Connecting Blynk"); }
Blynk.connect();
return 1;
}
else
{
if(debug) { Serial.print("Error received: "); }
if(debug) { Serial.println(contents[0]); }
return 0;
}
}
}