[Flutter] 통신 - 인터셉터

류재성's avatar
May 12, 2024
[Flutter] 통신 - 인터셉터
 
 

1. 인터셉터란?

💡
인터셉터(interceptor)는 주로 HTTP 통신을 처리할 때 사용되는 개념이다. 인터셉터는 네트워크 요청이나 응답을 가로채어 추가적인 처리를 할 수 있는 기능을 제공한다. 예를 들어, 모든 HTTP 요청에 공통적으로 헤더를 추가하거나, 응답을 받았을 때 특정 로직을 실행하고 싶을 때 인터셉터를 사용할 수 있다.
 
 
 

2. 인터셉터 적용 전

 
_core/config/http.dart
import 'package:dio/dio.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; // mac : ipconfig getifaddr en0 final dio = Dio( BaseOptions( baseUrl: "http://192.168.11.171:8080", // IPConfig 로 ip 확인하기⁷ contentType: "application/json; charset=utf-8", validateStatus: (status) => true, // 200 이 아니어도 예외 발생안하게 설정 ), ); const secureStorage = FlutterSecureStorage();
 
notion image
notion image
 
💡
인터셉터 적용 전은 매번 ViewModel 에서 세션에 접근해 토큰을 헤더에 넣어 통신을 해야 했다.
 
 

3. 인터셉터 적용 후

 
_core/config/http.dart
import 'package:dio/dio.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; // mac : ipconfig getifaddr en0 final dio = Dio( BaseOptions( baseUrl: "http://192.168.11.171:8080", // IPConfig 로 ip 확인하기⁷ contentType: "application/json; charset=utf-8", validateStatus: (status) => true, // 200 이 아니어도 예외 발생안하게 설정 ), ); const secureStorage = FlutterSecureStorage(); // 인터셉터 생성 var interceptor = InterceptorsWrapper( onRequest: (options, handler) async { //토큰을 secureStorage에서 읽는다. var accessToken = await secureStorage.read(key: 'accessToken'); print("onRequest 토큰: $accessToken"); if (accessToken != null) { options.headers["Authorization"] = "Bearer $accessToken"; } else { print("나 토큰이 없어"); } return handler.next(options); }, onResponse: (response, handler) async { var authorizationHeader = response.headers["Authorization"]; if (authorizationHeader != null) { var accessToken = authorizationHeader[0].split("Bearer ")[1]; print("onResponse 토큰: " + accessToken); await secureStorage.write(key: "accessToken", value: accessToken); } return handler.next(response); }, onError: (error, handler) { //요청, 응답 오류일때 return handler.next(error); }, );
 
notion image
 
notion image
 
💡
매 코드에 토큰을 보내지 않아도 인터셉터가 자동으로 토큰을 포함해서 통신한다.
Share article
RSSPowered by inblog