send method

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

Sends an HTTP request and asynchronously returns the response.

Implementation

@override
Future<StreamedResponse> send(BaseRequest request) async {
  var bytes = await request.finalize().toBytes();
  var xhr = HttpRequest();
  _xhrs.add(xhr);
  xhr
    ..open(request.method, '${request.url}', async: true)
    ..responseType = 'arraybuffer'
    ..withCredentials = withCredentials;
  request.headers.forEach(xhr.setRequestHeader);

  var completer = Completer<StreamedResponse>();

  unawaited(xhr.onLoad.first.then((_) {
    var body = (xhr.response as ByteBuffer).asUint8List();
    completer.complete(StreamedResponse(
        ByteStream.fromBytes(body), xhr.status!,
        contentLength: body.length,
        request: request,
        headers: xhr.responseHeaders,
        reasonPhrase: xhr.statusText));
  }));

  unawaited(xhr.onError.first.then((_) {
    // Unfortunately, the underlying XMLHttpRequest API doesn't expose any
    // specific information about the error itself.
    completer.completeError(
        ClientException('XMLHttpRequest error.', request.url),
        StackTrace.current);
  }));

  xhr.send(bytes);

  try {
    return await completer.future;
  } finally {
    _xhrs.remove(xhr);
  }
}