Set timeout for HTTPClient get() request

后端 未结 3 889
温柔的废话
温柔的废话 2020-12-09 07:41

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

  void _getSimpleReply( String command, callback, errorCallback )          


        
相关标签:
3条回答
  • 2020-12-09 08:08

    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);
    
    0 讨论(0)
  • 2020-12-09 08:15

    You can use timeout

    http.get('url').timeout(
      Duration(seconds: 1),
      onTimeout: () {
        // time has run out, do what you wanted to do
        return null;
      },
    );
    
    0 讨论(0)
  • 2020-12-09 08:26

    There is no option to set timeout using Dart's http. However, as it returns Future, we can set timeout on the Future.

    The example below sets timeout to 15 second. If it has been 15 seconds and no response received, it will throw TimeoutException

    Future<dynamic> postAPICall(String url, Map param, BuildContext context) async {
      try {
        final response =  await http.post(url,
            body: param).timeout(const Duration(seconds: 10),onTimeout : () {
          throw TimeoutException('The connection has timed out, Please try again!');
        });
    
        print("Success");
        return response;
      } on SocketException {
        print("You are not connected to internet");
      }
    }
    
    0 讨论(0)
提交回复
热议问题