본문 바로가기

Android

Android Retrofit 인터셉터 사용하기

1 서론


인터셉터란 작업의 요청을 가로챈후 특정 작업을 하기위한 용도로 사용되는 역활을 수행한다.
예로 요청을 수행할때 로그를 출력한다거나
요청을 할때 반드시 필요한 선행작업이있다면 인터셉터를 사용하여 처리하는경우가있다.

이 글에서는 로깅 작업과 필수파라미터 를 인터셉터로 처리해볼것이다.


2 준비 작업


2.1 의존성 추가

implementation 'com.squareup.okhttp3:logging-interceptor:4.8.1'

2.3 Retrofit Client 준비

object RetrofitClient {
    private  var retrofitClient: Retrofit?=null

    fun getClient(baseUrl:String):Retrofit?{

        if(retrofitClient == null){
            retrofitClient = Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
        }
        return retrofitClient
    }
}

위와같이 베이직한 RetrofitClient 가있을때 이곳에 인터셉터를 구현할것이다.

3 로깅 인터셉션


Retrofit 를 활용하여 API 통신을 할때
네트워크의 흐름을 파악하기위한 로깅 을 인터셉터를 활용하여 출력할것이다.

3.1 Extension 만들기

fun String?.isJsonObject():Boolean{
    return this?.startsWith("{") ==true && this.endsWith("}")
}
fun String?.isJsonArray():Boolean{
    return this?.startsWith("[") ==true && this.endsWith("]")
}

이 코드는 response 데이터가 JSON 의 형태인지 JSON Array 의 형태인지 파악하기위해 작성하였다.
반드시 필요한것은 아니다.

3.2 Retrofit Client 에 인터셉터 추가

fun getClient(baseUrl:String):Retrofit?{

	val client = OkHttpClient.Builder()

	val loggingInterceptor = HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger {
		override fun log(message: String) {
			when {
				message.isJsonObject() ->
					Log.d(TAG, JSONObject(message).toString(4))
				message.isJsonArray() ->
					Log.d(TAG, JSONObject(message).toString(4))
				else -> {
					try {
						Log.d(TAG, JSONObject(message).toString(4))
					} catch (e: Exception) {
						Log.d(TAG, message)
					}
				}
			}
		}

	})
	loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
	client.addInterceptor(loggingInterceptor)
	
	if(retrofitClient == null){
		retrofitClient = Retrofit.Builder()
			.baseUrl(baseUrl)
			.addConverterFactory(GsonConverterFactory.create())
			.client(client.build())
			.build()
	}
	return retrofitClient
}

먼저 OkHttpClient 를 생성한다. 그후 HttpLoggingInterceptor 를 생성하여 Console 에 Log 를 남기도록한다.
loggingInterceptor 의 Level 을 설정하면 로깅 인터셉터 완성이다.

그렇게 만들어진 HttpLoggingInterceptor를 OkHttpClient 에 추가한후
OkHttpClient 를 RetrofitClient에 추가한다.

4 파리미터 인터셉션


API 요청시 변하는 데이터가 아닌 특수한 Key 값이나 JWT 와 같이
고정적으로 필요한 데이터가 있을수있다.
이때 인터셉터를 이용해서 직접 매번 넣어주는것이 아닌 자동으로 넣어줄것이다

4.1 object 만들기

object API{
    const val BASE_URL :String ="https://api.test.com/"
    const val KEY :String ="DFf5onmix37b0ChMS6AIzf1oHYc"
}

관리를 위해 따로 object로 Key 를 빼두었다.



4.2 Retrofit Client 에 인터셉터 추가

fun getClient(baseUrl:String):Retrofit?{

	val client = OkHttpClient.Builder()

	var baseParameterInterceptor : Interceptor = (object : Interceptor{
		override fun intercept(chain: Interceptor.Chain): Response {
			val originalRequest = chain.request()

			val addedUrl = originalRequest.url.newBuilder().addQueryParameter("client_key", API.KEY).build()
			val finalRequest = originalRequest.newBuilder()
					.url(addedUrl)
					.method(originalRequest.method,originalRequest.body)
					.build()
			return chain.proceed(finalRequest)
		}

	})
	client.addInterceptor(baseParameterInterceptor)
	
	if(retrofitClient == null){
		retrofitClient = Retrofit.Builder()
			.baseUrl(baseUrl)
			.addConverterFactory(GsonConverterFactory.create())
			.client(client.build())
			.build()
	}
	return retrofitClient
}

먼저 기본 Request 객체를 chain 에서 얻어온후
newBuilder 을 통해 Parameter을 넣는 모습을 볼수있다.
여기서 모든 API 통신에 사용할 KEY 를 넣는다.
그후 나머지를 기본 Request 로 넣어준후 반환해주는것으로 인터셉터 구현이 끝이난다

이렇게 만들어진 인터셉터를 OkHttpClient 에 추가한후
OkHttpClient 를 RetrofitClient에 추가한다.
이렇게 하는것으로
원하는 데이터를 인터셉터를 사용하여 넣어줄수있었다.