download function

Stream<List<int>> download(
  1. Uri uri, {
  2. void headers(
    1. HttpHeaders
    )?,
  3. void cookies(
    1. List<Cookie>
    )?,
  4. bool isSuccessfulStatusCode(
    1. int
    ) = _isSuccessfulStatusCode,
  5. SecurityContext? context,
  6. Duration connectionTimeout = const Duration(seconds: 10),
})

Download binary data from the given Uri.

It is possible to configure HttpHeaders and Cookies sent to the server by providing the functions headers and cookies, respectively.

A response is considered successful if the isSuccessfulStatusCode function returns true. If it is not, an HttpCodeException is thrown. By default, defaultSuccessfulStatusCodes is used.

A connectionTimeout may be provided.

This method opens a single connection to make a GET request, and closes that connection before returning, so it is not suitable for making several requests to the same server efficiently.

Implementation

Stream<List<int>> download(Uri uri,
    {void Function(HttpHeaders)? headers,
    void Function(List<Cookie>)? cookies,
    bool Function(int) isSuccessfulStatusCode = _isSuccessfulStatusCode,
    SecurityContext? context,
    Duration connectionTimeout = const Duration(seconds: 10)}) async* {
  final client = HttpClient(context: context)
    ..connectionTimeout = connectionTimeout;
  final req = await client.getUrl(uri);
  try {
    req.persistentConnection = false;
    headers?.call(req.headers);
    cookies?.call(req.cookies);
    final res = await req.close();
    if (isSuccessfulStatusCode(res.statusCode)) {
      yield* res;
    } else {
      throw HttpCodeException(res, uri);
    }
  } finally {
    client.close(force: true);
  }
}