为 HTTPClientget()请求设置超时

此方法提交一个简单的 HTTP 请求,并调用一个成功或错误回调函数:

  void _getSimpleReply( String command, callback, errorCallback ) async {


try {


HttpClientRequest request = await _myClient.get( _serverIPAddress, _serverPort, '/' );


HttpClientResponse response = await request.close();


response.transform( utf8.decoder ).listen( (onData) { callback( onData ); } );


} on SocketException catch( e ) {


errorCallback( e.toString() );


}
}

如果服务器没有运行,Android 应用程序或多或少会立即调用 errorCallback。

在 iOS 上,errorCallback 需要很长的时间——超过20秒——直到调用任何回调。

我是否可以为 HttpClient ()设置等待服务器端返回答复的最大秒数(如果有的话) ?

72338 次浏览

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);

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
},
);

The HttpClient.connectionTimeout didn't work for me. However, I knew that the Dio packet allows request cancellation. Then, I dig into the packet to find out how they achieve it and I adapted it to me. What I did was to create two futures:

  • A Future.delayed where I set the duration of the timeout.
  • The HTTP request.

Then, I passed the two futures to a Future.any which returns the result of the first future to complete and the results of all the other futures are discarded. Therefore, if the timeout future completes first, your connection times out and no response will arrive. You can check it out in the following code:

Future<Response> get(
String url, {
Duration timeout = Duration(seconds: 30),
}) async {
    

final request = Request('GET', Uri.parse(url))..followRedirects = false;
headers.forEach((key, value) {
request.headers[key] = value;
});


final Completer _completer = Completer();


/// Fake timeout by forcing the request future to complete if the duration
/// ends before the response arrives.
Future.delayed(timeout, () => _completer.complete());


final response = await Response.fromStream(await listenCancelForAsyncTask(
_completer,
Future(() {
return _getClient().send(request);
}),
));
}
    

Future<T> listenCancelForAsyncTask<T>(
Completer completer,
Future<T> future,
) {
/// Returns the first future of the futures list to complete. Therefore,
/// if the first future is the timeout, the http response will not arrive
/// and it is possible to handle the timeout.
return Future.any([
if (completer != null) completeFuture(completer),
future,
]);
}


Future<T> completeFuture<T>(Completer completer) async {
await completer.future;
throw TimeoutException('TimeoutError');
}

This is an example of how to extend the http.BaseClient class to support timeout and ignore the exception of the S.O. if the client's timeout is reached first. you just need to override the "send" method...

the timeout should be passed as a parameter to the class constructor.

import 'dart:async';
import 'package:http/http.dart' as http;


// as dart does not support tuples i create an Either class
class _Either<L, R> {
final L? left;
final R? right;


_Either(this.left, this.right);
_Either.Left(L this.left) : right = null;
_Either.Right(R this.right) : left = null;
}


class TimeoutClient extends http.BaseClient {
final http.Client _httpClient;
final Duration timeout;


TimeoutClient(
{http.Client? httpClient, this.timeout = const Duration(seconds: 30)})
: _httpClient = httpClient ?? http.Client();


Future<http.StreamedResponse> send(http.BaseRequest request) async {
// wait for result between two Futures (the one that is reached first) in silent mode (no throw exception)
_Either<http.StreamedResponse, Exception> result = await Future.any([
Future.delayed(
timeout,
() => _Either.Right(
TimeoutException(
'Client connection timeout after ${timeout.inMilliseconds} ms.'),
)),
Future(() async {
try {
return _Either.Left(await _httpClient.send(request));
} on Exception catch (e) {
return _Either.Right(e);
}
})
]);


// this code is reached only for first Future response,
// the second Future is ignorated and does not reach this point
if (result.right != null) {
throw result.right!;
}


return result.left!;
}
}


You can also choose to override the settings for a HttpClient:

class DevHttpOverrides extends HttpOverrides {
  

@override
HttpClient createHttpClient(SecurityContext? context) {
return super.createHttpClient(context)
..connectionTimeout = Duration(seconds: 2);
}
}

Their is onError option which works fine if their is any exception like no internet.It has to return response(my case in below code) or null. In response their are 2 options Body and Status code.

var response = await http.post(url, body: body, headers: _headers).onError(
(error, stackTrace) => http.Response(
jsonEncode({
'message':no internet please connect to internet first
}),
408));