Set the timeout - Ethernet Shield library
In the stream class there is a setTimeout(ms) function. e.g.

String str;
Serial.setTimeout(5000) ;
str = Serial.readStringUntil('\r');


Where this does timeout the initial connection attempt in http.connect(). Whereas I found it also important to timeout each line, as a web page may not disconnect at the end or not send anything.

int httpGetHeaders() {
  String request, response;
  int result = 0;
  long startOfHttpResponseTime;

  client.setTimeout(1000) ;
  response = "";
  inHeaders = true;
  startOfHttpResponseTime = millis();
  while((client.connected()) &amp;&amp; inHeaders &amp;&amp; ((long)(millis() - startOfHttpResponseTime) &lt; HTTP_RESPONSE_TIMEOUT)) {
    String header = client.readStringUntil('\n');
    header.trim(); // trim off white spaces including CR and LF at end.
    Serial.print(F("head[")); 
    Serial.print(header.length()); 
    Serial.print(F("]:\"")); 
    Serial.print(header);
    Serial.println(F("\"")); 
    if (!header.length()) { // first blank line indicates end of headers
      inHeaders = false;
      Serial.println(F("No longer in Headers")); 
    }
    else {
      if (header.startsWith("HTTP")) {
        Serial.println(F("HTTP Found")); 
        int firstspace = header.indexOf(" ");
        result = header.substring(firstspace + 1, header.indexOf(" ", firstspace + 1)).toInt();
        Serial.print(F("result = ")); 
        Serial.println(result); 
      }
    }
  }

  Serial.print(F("Result code = "));
  Serial.println(result);
  return result;
}


You may want to review the whole code at https://github.com/lansing-makers-network/StatusBotArduino/blob/master/StatusBotArduino.ino I have reduced the connection to a sequence of commands that can be used consectutively in the desired order to meet different needs. The above is just to read a headers response.