Set timeout for HTTPClient get() request
You can use timeout
http.get(Uri.parse('url')).timeout(
const Duration(seconds: 1),
onTimeout: () {
// Time has run out, do what you wanted to do.
return http.Response('Error', 408); // Request Timeout response status code
},
);
There are two different ways to configure this behavior in Dart
Set a per request timeout
You can set a timeout on any Future using the Future.timeout
method. This will short-circuit after the given duration has elapsed by throwing a TimeoutException
.
try {
final request = await client.get(...);
final response = await request.close()
.timeout(const Duration(seconds: 2));
// rest of the code
...
} on TimeoutException catch (_) {
// A timeout occurred.
} on SocketException catch (_) {
// Other exception
}
Set a timeout on HttpClient
You can also set a timeout on the HttpClient itself using HttpClient.connectionTimeout
. This will apply to all requests made by the same client, after the timeout was set. When a request exceeds this timeout, a SocketException
is thrown.
final client = new HttpClient();
client.connectionTimeout = const Duration(seconds: 5);