interceptRequest method

  1. @override
FutureOr<BaseRequest> interceptRequest({
  1. required BaseRequest request,
})

Runs before the request is sent. Return the (possibly modified) request.

Implementation

@override
FutureOr<BaseRequest> interceptRequest({required BaseRequest request}) {
  // `http_interceptor` v3 re-sends the *same* `BaseRequest` instance on a
  // retry (e.g. a token-refresh `RetryPolicy`), so the inner client calls
  // `finalize()` on it twice and throws `Bad state: Can't finalize a
  // finalized Request`. As the last interceptor, the request we return is
  // the one actually sent — so hand back a fresh copy on every call, giving
  // each attempt (including retries) an unfinalized request to finalize.
  //
  // Only plain `Request`s can be copied safely; multipart / streamed bodies
  // are one-shot streams (and aren't retriable), so we pass those through.
  final sent = request is Request ? _copyHttpRequest(request) : request;

  final network = _networkOrNull();
  if (network != null) {
    try {
      final body = sent is Request ? sent.body : null;
      final nf = network.start(
        method: sent.method,
        url: urlFor?.call(sent) ?? sent.url.toString(),
        requestHeaders: Map<String, String>.from(sent.headers),
        requestBody: body == null ? null : _cap(body),
        requestBodySize: body?.length ?? sent.contentLength,
      );
      // Correlate by both the sent copy (what `interceptResponse` sees on
      // `response.request`) and the incoming request (what a `RetryPolicy`
      // exception hook receives), so both paths find this handle.
      _inFlight[sent] = nf;
      if (!identical(sent, request)) _inFlight[request] = nf;
    } catch (_) {
      // Never let logging take down the actual HTTP call.
    }
  }
  return sent;
}