为 HTTPClient get() 请求设置超时

为 HTTPClient get() 请求设置超时

问题描述:

此方法提交一个简单的 HTTP 请求并调用成功或错误回调就好了:

This method submits a simple HTTP request and calls a success or error callback just fine:

  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.

If the server isn't running, the Android-app more or less instantly calls the errorCallback.

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

On iOS, the errorCallback takes a very long period of time - more than 20 seconds - until any callback gets called.

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

在 Dart 中有两种不同的方式来配置这个行为

There are two different ways to configure this behavior in Dart

您可以使用 Future.timeout 方法.在给定的持续时间过后,这将通过抛出 TimeoutException 来短路.

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
}

在 HttpClient 上设置超时

您还可以使用 HttpClient.connectionTimeout.在设置超时后,这将适用于同一客户端发出的所有请求.当请求超过此超时时间时,将抛出 SocketException.

final client = new HttpClient();
client.connectionTimeout = const Duration(seconds: 5);