fetch method

  1. @override
Future<ResponseBody> fetch(
  1. RequestOptions options,
  2. Stream<Uint8List>? requestStream,
  3. Future? cancelFuture
)
override

We should implement this method to make real http requests.

options: The request options

requestStream The request stream, It will not be null only when http method is one of "POST","PUT","PATCH" and the request body is not empty.

We should give priority to using requestStream(not options.data) as request data. because supporting stream ensures the onSendProgress works.

cancelFuture: When cancelled the request, cancelFuture will be resolved! you can listen cancel event by it, for example:

 cancelFuture?.then((_)=>print("request cancelled!"))

cancelFuture: will be null when the request is not set CancelToken.

Implementation

@override
Future<ResponseBody> fetch(RequestOptions options,
    Stream<Uint8List>? requestStream, Future? cancelFuture) {
  var xhr = HttpRequest();
  _xhrs.add(xhr);

  xhr
    ..open(options.method, options.uri.toString(), async: true)
    ..responseType = 'blob'
    ..withCredentials = options.extra['withCredentials'] ?? withCredentials;
  options.headers.remove(Headers.contentLengthHeader);
  options.headers.forEach((key, v) => xhr.setRequestHeader(key, '$v'));

  var completer = Completer<ResponseBody>();

  xhr.onLoad.first.then((_) {
    // TODO: Set the response type to "arraybuffer" when issue 18542 is fixed.
    var blob = xhr.response ?? Blob([]);
    var reader = FileReader();

    reader.onLoad.first.then((_) {
      var body = reader.result as Uint8List;
      completer.complete(
        ResponseBody.fromBytes(
          body,
          xhr.status,
          headers:
              xhr.responseHeaders.map((k, v) => MapEntry(k, v.split(','))),
          statusMessage: xhr.statusText,
          isRedirect: xhr.status == 302 || xhr.status == 301,
        ),
      );
    });

    reader.onError.first.then((error) {
      completer.completeError(
        DioError(
          type: DioErrorType.response,
          error: error,
          requestOptions: options,
        ),
        StackTrace.current,
      );
    });
    reader.readAsArrayBuffer(blob);
  });

  xhr.onError.first.then((_) {
    // Unfortunately, the underlying XMLHttpRequest API doesn't expose any
    // specific information about the error itself.
    completer.completeError(
      DioError(
        type: DioErrorType.response,
        error: 'XMLHttpRequest error.',
        requestOptions: options,
      ),
      StackTrace.current,
    );
  });

  cancelFuture?.then((_) {
    if (xhr.readyState < 4 && xhr.readyState > 0) {
      try {
        xhr.abort();
      } catch (e) {
        // ignore
      }
    }
  });

  if (requestStream != null) {
    requestStream
        .reduce((a, b) => Uint8List.fromList([...a, ...b]))
        .then(xhr.send);
  } else {
    xhr.send();
  }

  return completer.future.whenComplete(() {
    _xhrs.remove(xhr);
  });
}