http_interceptor는 HTTP 요청과 응답을 가로채는 데 사용할 수 있는 경량 플러터 플러그인으로, 헤더 추가, 로깅 또는 전역 오류 처리와 같은 수정 작업을 가능하게 합니다. 인증 토큰 삽입, 요청/응답 로깅, 앱 전체의 오류 처리와 같은 일반적인 작업을 간소화합니다. 내장된 http 클라이언트와 원활하게 통합되며 Android, iOS, Web, macOS, Windows, Linux 등 주요 플랫폼을 지원합니다. 단순성과 유연성을 고려하여 복잡한 설정 없이 미들웨어 스타일의 가로채기용 명확한 API를 제공합니다.
사용 사례
전역 요청 헤더 수정
인증 토큰 주입
요청/응답 로깅
앱 전체에서의 오류 처리
API 요청 모니터링
HTTP 트래픽 디버깅
주요 기능
간단한 미들웨어 스타일의 가로채기
요청과 응답 둘 다 지원
크로스 플랫폼 호환성
HTTP 클라이언트와의 간편한 통합
최소한의 보일러플레이트
확장 가능한 인터셉터 체인
적합한 대상
중앙화된 HTTP 로직이 필요한 앱
인증 흐름을 구현하는 개발자
디버그 친화적인 HTTP 추적을 필요로 하는 팀
자주 API 상호작용이 있는 프로젝트
경량 HTTP 유틸리티를 찾는 사람
고려 사항
HTTP 라이프사이클에 대한 이해 필요
과도하게 사용할 경우 성능에 영향을 줄 수 있습니다
기본적으로 인터셉터는 동기적으로 실행됩니다
제한된 내장 오류 복구
복잡한 라우팅 또는 캐싱을 위한 것이 아님
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
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!