onRequest method

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

Intercepts outgoing HTTP requests made using Dio.

This method logs request details using the Infospect system before the actual request is made.

  • options: The request options.
  • handler: A request interceptor handler, which determines how the request should be handled.

Implementation

@override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
  try {
    InfospectNetworkCall call = InfospectNetworkCall(options.hashCode);
    InfospectNetworkRequest request = InfospectNetworkRequest();

    final Uri uri = options.uri;

    String body = '';
    int size = 0;
    List<InfospectFormDataField>? formDataFields;
    List<InfospectFormDataFile>? formDataFiles;
    if (options.data != null) {
      if (options.data is FormData) {
        body += "Form data";

        if (options.data.fields.isNotEmpty == true) {
          final List<InfospectFormDataField> fields = [];
          for (var entry in options.data.fields) {
            fields.add(InfospectFormDataField(entry.key, entry.value));
          }
          formDataFields = fields;
        }
        if (options.data.files.isNotEmpty == true) {
          final List<InfospectFormDataFile> files = [];
          for (var entry in options.data.files) {
            files.add(
              InfospectFormDataFile(
                entry.value.filename,
                entry.value.contentType.toString(),
                entry.value.length,
              ),
            );
          }

          formDataFiles = files;
        }
      } else {
        size = utf8.encode(options.data.toString()).length;
        body = options.data.toString();
      }
    }

    request = request.copyWith(
      headers: options.headers,
      contentType: options.contentType.toString(),
      queryParameters: options.queryParameters,
      formDataFields: formDataFields,
      formDataFiles: formDataFiles,
      body: body,
      size: size,
    );

    infospect.addCall(call.copyWith(
      request: request,
      secure: uri.scheme == "https",
      method: options.method,
      endpoint: options.uri.path,
      server: uri.host,
      client: 'Dio',
      uri: options.uri.toString(),
    ));
  } catch (e, st) {
    infospect.addLog(
      InfospectLog(
        message: e.toString(),
        stackTrace: st,
        error: e,
        level: DiagnosticLevel.error,
      ),
    );
  }
  handler.next(options);
}