send method

  1. @override
Future<StreamedResponse> send(
  1. BaseRequest request
)

Sends an HTTP request and asynchronously returns the response.

Implementers should call BaseRequest.finalize to get the body of the request as a ByteStream. They shouldn't make any assumptions about the state of the stream; it could have data written to it asynchronously at a later point, or it could already be closed when it's returned. Any internal HTTP errors should be wrapped as ClientExceptions.

Implementation

@override
Future<http.StreamedResponse> send(http.BaseRequest request) async {
  if (_closed) {
    throw http.ClientException('The client is closed', request.url);
  }
  Future<void>? abort = request is http.Abortable
      ? request.abortTrigger
      : null;
  bool aborted = false;
  if (abort != null) {
    unawaited(abort.then((_) => aborted = true));
    // a trigger that is complete now: the request must not go out
    await null;
  }
  int? length = request.contentLength;
  Stream<List<int>> body = request.finalize();
  if (aborted) throw _aborted(body, request.url);
  // the native client sets these two itself
  Map<String, String> headers = <String, String>{};
  for (MapEntry<String, String> header in request.headers.entries) {
    String name = header.key.toLowerCase();
    if (name == 'content-length' || name == 'transfer-encoding') continue;
    headers[header.key] = header.value;
  }
  // No body: the native client then follows redirects and can send the
  // request again. It sends `content-length: 0` for POST, PUT and PATCH.
  bool empty = length == 0;
  if (empty) {
    body.drain<void>().ignore();
  } else if (length == null) {
    // A stream with no length can be empty, like a GET that is sent as a
    // StreamedRequest. Wait for its first bytes: with none, the request
    // has no body.
    // `rest` keeps the parts in their sequence until the native client
    // listens to it.
    Completer<bool> first = Completer<bool>();
    StreamController<List<int>> rest = StreamController<List<int>>();
    StreamSubscription<List<int>>? sub;
    sub = body.listen(
      (List<int> part) {
        if (part.isEmpty && !first.isCompleted) return;
        rest.add(part);
        if (first.isCompleted) return;
        // null: the part came while `listen` ran, see below
        sub?.pause();
        first.complete(true);
      },
      onError: (Object error, StackTrace trace) {
        if (first.isCompleted) return rest.addError(error, trace);
        first.completeError(error, trace);
      },
      onDone: () {
        rest.close();
        if (!first.isCompleted) first.complete(false);
      },
    );
    StreamSubscription<List<int>> source = sub;
    if (first.isCompleted) source.pause();
    rest
      ..onListen = source.resume
      ..onPause = source.pause
      ..onResume = source.resume
      ..onCancel = source.cancel;
    bool some;
    try {
      some = abort == null
          ? await first.future
          : await Future.any<bool>(<Future<bool>>[
              first.future,
              abort.then((_) => false),
            ]);
    } on Object {
      // the body failed before its first bytes
      source.cancel().ignore();
      rethrow;
    }
    if (aborted) {
      first.future.ignore();
      source.cancel().ignore();
      throw http.RequestAbortedException(request.url);
    }
    if (some) {
      body = rest.stream;
    } else {
      empty = true;
    }
  }
  DoxHttpClientStreamedResponse res;
  try {
    res = await _client.sendStreamed(
      request.method,
      request.url,
      headers: headers,
      body: empty ? null : body,
      contentLength: empty ? null : length,
      followRedirects: request.followRedirects,
      maxRedirects: request.maxRedirects,
      abort: abort,
    );
  } on DoxHttpClientException catch (e) {
    throw _failure(e);
  } on Object {
    // eg. a URL that is not http: the body was not read
    if (!empty) _drop(body);
    rethrow;
  }
  String? size = res.headers['content-length'];
  return http.StreamedResponse(
    res.body.transform(
      StreamTransformer<Uint8List, List<int>>.fromHandlers(
        handleError:
            (Object error, StackTrace trace, EventSink<List<int>> sink) {
              sink.addError(
                error is DoxHttpClientException ? _failure(error) : error,
                trace,
              );
            },
      ),
    ),
    res.statusCode,
    contentLength: size == null ? null : int.tryParse(size),
    request: request,
    headers: res.headers,
    reasonPhrase: res.reasonPhrase,
    isRedirect:
        _redirects.contains(res.statusCode) &&
        res.headers.containsKey('location'),
  );
}