onRequest method

  1. @override
Future<void> onRequest(
  1. RequestContext ctx,
  2. RequestOptions options
)
override

请求发送前调用(可修改 RequestOptions)

Implementation

@override
Future<void> onRequest(RequestContext ctx, RequestOptions options) async {
  // 从所有提供器获取 headers
  for (final provider in _providers) {
    final headers = await provider();
    for (final entry in headers.entries) {
      final key = entry.key;
      final value = entry.value;

      // 跳过 null 值
      if (value == null) continue;

      // 如果开启 skipEmpty,跳过空字符串
      if (skipEmpty && (key.isEmpty || value.isEmpty)) continue;

      // 仅在请求没有指定该头部时添加
      if (!options.headers.containsKey(key) &&
          !(ctx.request.headers?.containsKey(key) ?? false)) {
        options.headers[key] = value;
      }
    }
  }

  // 添加请求级头部(覆盖固定头部)
  if (ctx.request.headers != null) {
    options.headers.addAll(ctx.request.headers!);
  }
}