Set timeout for HTTPClient get() request

后端 未结 3 890
温柔的废话
温柔的废话 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: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 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");
      }
    }
    

提交回复
热议问题