Proper way of setting request timeout for Flutter http requests?

724

With the raw HttpClient API from dart:io, you can cancel an HTTP request by calling HttpClientRequest.abort when your Future times out:

import 'dart:async';
import 'dart:io' as io;

Future<void> main(List<String> args) async {
  var slowUrl = args.first;
  var httpClient = io.HttpClient();
  var request = await httpClient.getUrl(Uri.parse(slowUrl));
  try {
    var response = await request
        .close()
        .then(
          (_) => print('Got eventual response'),
        )
        .timeout(
          const Duration(seconds: 1),
        );
  } on TimeoutException catch (_) {
    print('Timed out');
    request.abort();
  }
}

When run with with an URL with a slow response, the above should print "Timed out" and not "Got eventual response".

However, HttpClientRequest.abort is (as of writing) a somewhat recent addition, and currently it is not exposed in package:http.

Share:
724
ch271828n
Author by

ch271828n

Hello, world :)

Updated on December 31, 2022

Comments

  • ch271828n
    ch271828n over 1 year

    I need to set a timeout for http requests.

    I have read Set timeout for HTTPClient get() request and it suggests us to use http.get(...).timeout(...).

    However, I am worried: that .timeout is a method in Future class. Therefore, even if it timeouts, the http request is still ongoing! In other words, if the http request actually needs, say, 30 seconds to finish, and we use timeout(Duration(seconds: 5)), then even if it seems as if we have aborted the request, it is actually still costing resources of the phone of the user for another 25 seconds.

    Therefore, I would appreciate it if there is a proper way to timeout requests. Or, please correct me if I am wrong.

    P.S. I know there is another thing, HttpClient.connectionTimeout. That is for connecting phase, not the time of whole request. Interestingly, when I go into the source code see here, I find that it also uses some_future.timeout() internally. Therefore, the resources, IMHO, are also not released when timeout.