fetch method

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

Implement this method to make real HTTP requests.

options are the request options.

requestStream is the request stream. It will not be null only when the request body is not empty. Use requestStream if your code rely on RequestOptions.onSendProgress.

cancelFuture corresponds to CancelToken handling. When the request is canceled, cancelFuture will be resolved. To await if a request has been canceled:

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

Implementation

@override
Future<ResponseBody> fetch(
  RequestOptions options,
  Stream<Uint8List>? requestStream,
  Future<void>? cancelFuture,
) async {
  // Recursive fetching.
  final redirects = <RedirectRecord>[];
  try {
    return await _fetch(options, requestStream, cancelFuture, redirects);
  } on DioH2NotSupportedException catch (e) {
    // Fallback to use the callback
    // or to another adapter (typically IOHttpClientAdapter)
    // since the request can have a better handle by it.
    if (onNotSupported != null) {
      return await onNotSupported!(options, requestStream, cancelFuture, e);
    }
    return await fallbackAdapter.fetch(options, requestStream, cancelFuture);
  } on SocketException catch (e) {
    if (e.message.contains('timed out')) {
      final Duration effectiveTimeout;
      if (options.connectTimeout != null &&
          options.connectTimeout! > Duration.zero) {
        effectiveTimeout = options.connectTimeout!;
      } else {
        effectiveTimeout = Duration.zero;
      }
      throw DioException.connectionTimeout(
        requestOptions: options,
        timeout: effectiveTimeout,
        error: e,
      );
    }
    throw DioException.connectionError(
      requestOptions: options,
      reason: e.message,
      error: e,
    );
  }
}