// retrofit2
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
// OkHttp
implementation 'com.squareup.okhttp3:okhttp:4.9.0'
implementation 'com.squareup.okhttp3:logging-interceptor:4.9.0'
public class HeaderInterceptor implements Interceptor {
private static final String TAG = "HeaderInterceptor";
private String token;
public HeaderInterceptor(String token) {
this.token = token;
}
@NotNull
@Override
public Response intercept(@NotNull Chain chain) throws IOException {
Log.d(TAG, "intercept: 실행됨");
token = SessionUser.token;
Request request = chain.request().newBuilder()
.addHeader("Authorization", token).build();
return chain.proceed(request);
}
}
public interface PostService {
OkHttpClient client = new OkHttpClient.Builder().
addInterceptor(new HeaderInterceptor(SessionUser.token)).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("<http://localhost:8080>")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
PostService service = retrofit.create(PostService.class);
}
헤더에 따로 추가하지 않고 요청해도 정상적으로 응답이 오는 것을 확인할 수 있음
@GET("/post/{id}")
Call<CMRespDTO<Post>> findById(@Path("id")int postId);
참고
[Android] Retrofit을 이용한 토큰 인증 방식 구현](https://kimch3617.tistory.com/entry/Retrofit을-이용한-토큰-인증-방식-구현)