onRequest method

  1. @override
void onRequest(
  1. RequestOptions options,
  2. RequestInterceptorHandler handler
)
override

Called when the request is about to be sent.

Implementation

@override
void onRequest(
  RequestOptions options,
  RequestInterceptorHandler handler,
) async {
  final uri = options.uri;

  // Only validate HTTPS requests
  if (uri.scheme == 'https') {
    try {
      await _validateCertificate(uri.host, uri.port);
      // Certificate validation passed, proceed with request
      handler.next(options);
    } on TrustPinException catch (e) {
      // Certificate validation failed, reject the request
      handler.reject(
        DioException(
          requestOptions: options,
          error: e,
          type: DioExceptionType.connectionError,
          message: 'Certificate pinning validation failed',
        ),
      );
    } catch (e) {
      // Other errors during validation
      handler.reject(
        DioException(
          requestOptions: options,
          error: e,
          type: DioExceptionType.connectionError,
          message: 'Certificate pinning validation failed',
        ),
      );
    }
  } else {
    // Not HTTPS, proceed without validation
    handler.next(options);
  }
}