Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
670 views
in Technique[技术] by (71.8m points)

api - Set timeout for HTTPClient get() request

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

    }
  }

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

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

May I set for HttpClient() a maximum number of seconds to wait for the server side to return a reply - if any?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...