Aus öffentlichen Paketdaten erstellte Orientierung.
http_interceptor ist ein leichtgewichtiges Flutter-Plugin, das Entwicklern ermöglicht, HTTP-Anfragen und -Antworten zu erfassen, um Änderungen wie das Hinzufügen von Headern, Protokollierung oder die globale Fehlerbehandlung vorzunehmen. Es vereinfacht alltägliche Aufgaben wie die Einbindung von Authentifizierungstoken, das Protokollieren von Anfragen/Antworten sowie die Fehlerbehandlung über die gesamte App hinweg. Das Paket integriert sich nahtlos mit dem eingebauten http-Client und unterstützt alle wichtigen Plattformen wie Android, iOS, Web, macOS, Windows und Linux. Durch seine Einfachheit und Flexibilität bietet es eine klare API für Middleware-artige Interception ohne komplizierte Einrichtung.
Anwendungsfälle
Globale Änderung des Anforderungsheaders
Authentifizierungstoken-Injektion
Anfrage/Antwort-Protokollierung
Fehlerbehandlung im gesamten App
API-Anforderungsüberwachung
Debuggen von HTTP-Verkehr
Hauptmerkmale
Einfache Middleware-artige Interception
Unterstützt sowohl Anfragen als auch Antworten
Plattformübergreifende Kompatibilität
Einfache Integration mit HTTP-Client
Minimales Boilerplate
Erweiterbare Interceptor-Ketten
Geeignet für
Apps, die zentrale HTTP-Logik benötigen
Entwickler, die Authentifizierungsabläufe implementieren
Teams, die debugfreundliche HTTP-Tracking benötigen
Projekte mit häufigen API-Interaktionen
Diejenigen, die leichte HTTP-Tools suchen
Hinweise
Verständnis des HTTP-Lebenszyklus erforderlich
Kann die Leistung beeinträchtigen, wenn sie übermäßig verwendet wird
Interzeptoren werden standardmäßig synchron ausgeführt
Nicht für komplexe Routing- oder Caching-Aufgaben geeignet
Original-README
Originaler README-Schnappschuss aus dem verknüpften Quell-Repository. Aktuelle Inhalte finden Sie im Repository.
http_interceptor
This is a plugin that lets you intercept the different requests and responses from Dart's http package. You can use to add headers, modify query params, or print a log of the response.
Now that you actually have your interceptor implemented, now you need to use it. There are two general ways in which you can use them: by using the InterceptedHttp to do separate connections for different requests or using a InterceptedClient for keeping a connection alive while making the different http calls. The ideal place to use them is in the service/provider class or the repository class (if you are not using services or providers); if you don't know about the repository pattern you can just google it and you'll know what I'm talking about. 😉
Using interceptors with Client
Normally, this approach is taken because of its ability to be tested and mocked.
Here is an example with a repository using the InterceptedClient class.
The ResponseBodyDecoding extension adds a few lightweight helpers on Response for common JSON use cases:
final response = await client.get(
'$baseUrl/weather'.toUri(),
params: {'id': '$id'},
);
// Dynamically-typed JSON value (Map/List/primitive or null on empty body).finalObject? json = response.jsonBody;
// JSON object as a map (throws if body is empty or not a JSON object).finalMap<String, dynamic> data = response.jsonMap;
// JSON array as a list (throws if body is empty or not a JSON array).finalList<dynamic> items = response.jsonList;
Decoding responses into models
The ResponseBodyDecoding extension provides helpers to turn JSON responses into strongly-typed models with minimal boilerplate.
Sometimes you need to retry a request due to different circumstances, an expired token is a really good example. Here's how you could potentially implement an expired token retry policy with http_interceptor.
classExpiredTokenRetryPolicyextendsRetryPolicy{
@overrideintget maxRetryAttempts => 2;
@overrideboolshouldAttemptRetryOnException(Exception reason, BaseRequest request) {
// Log the exception for debuggingprint('Request failed: ${reason.toString()}');
print('Request URL: ${request.url}');
// Retry on network exceptions, but not on client errorsreturn reason isSocketException || reason isTimeoutException;
}
@overrideFuture<bool> shouldAttemptRetryOnResponse(BaseResponse response) async {
if (response.statusCode == 401) {
// Perform your token refresh here.print('Token expired, refreshing...');
returntrue;
}
returnfalse;
}
}
You can also set the maximum amount of retry attempts with maxRetryAttempts property or override the shouldAttemptRetryOnException if you want to retry the request after it failed with an exception.
RetryPolicy Interface
The RetryPolicy abstract class provides the following methods that you can override:
shouldAttemptRetryOnException(Exception reason, BaseRequest request): Called when an exception occurs during the request. Return true to retry, false to fail immediately.
shouldAttemptRetryOnResponse(BaseResponse response): Called after receiving a response. Return true to retry, false to accept the response.
maxRetryAttempts: The maximum number of retry attempts (default: 1).
delayRetryAttemptOnException({required int retryAttempt}): Delay before retrying after an exception (default: no delay).
delayRetryAttemptOnResponse({required int retryAttempt}): Delay before retrying after a response (default: no delay).
Using Retry Policies
To use a retry policy, pass it to the InterceptedClient or InterceptedHttp:
final client = InterceptedClient.build(
interceptors: [WeatherApiInterceptor()],
retryPolicy: ExpiredTokenRetryPolicy(),
);
Sometimes it is helpful to have a cool-down phase between multiple requests. This delay could for example also differ between the first and the second retry attempt as shown in the following example.
You can achieve support for self-signed certificates by providing InterceptedHttp or InterceptedClient with the client parameter when using the build method on either of those, it should look something like this:
Note: It is important to know that since both HttpClient and IOClient are part of dart:io package, this will not be a feature that you can perform on Flutter Web (due to BrowserClient and browser limitations).
We migrated our roadmap to better suit the needs for development since we use ClickUp as our task management tool.
Troubleshooting
Open an issue and tell me, I will be happy to help you out as soon as I can.
Contributions
Contributions are always welcomed and encouraged, we will always give you credit for your work on this section. If you are interested in maintaining the project on a regular basis drop me a line at [me@codingale.dev](mailto:me@codingale.dev).
Contributors
Thanks to all the wonderful people contributing to improve this package. Check the Emoji Key for reference on what means what!