onRequest method

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

Called when the request is about to be sent.

Implementation

@override
void onRequest(
  RequestOptions options,
  RequestInterceptorHandler handler,
) async {
  if (_rotateProxies || _currentProxy == null) {
    try {
      _currentProxy = _proxyManager.getNextProxy(
        validated: _useValidatedProxies,
      );
    } catch (e) {
      // If no proxies are available, try to fetch some
      try {
        if (_useValidatedProxies) {
          await _proxyManager.fetchValidatedProxies();
        } else {
          await _proxyManager.fetchProxies();
        }

        _currentProxy = _proxyManager.getNextProxy(
          validated: _useValidatedProxies,
        );
      } catch (_) {
        // If still no proxies, proceed without a proxy
        handler.next(options);
        return;
      }
    }
  }

  // Set up the proxy
  final proxy = _currentProxy!;

  // Set proxy for Dio
  final proxyUrl = '${proxy.ip}:${proxy.port}';
  options.headers['proxy'] = proxyUrl;
  options.extra['proxy'] = proxyUrl;

  // Add authentication if needed
  if (proxy.isAuthenticated) {
    final auth =
        'Basic ${base64Encode(utf8.encode('${proxy.username}:${proxy.password}'))}';
    options.headers['Proxy-Authorization'] = auth;
    options.extra['proxyAuth'] = auth;
  }

  // Reset retry count for new requests
  _retryCount = 0;

  handler.next(options);
}