본문 바로가기
개발노트/Android

[Kotlin] OKHttp Logging Interceptor사용하기

by 전지적진영시점 2023. 2. 20.
반응형

개발 환경

---------------------------------

OS : Mac

개발 툴 : Android Studio

개발 언어 : Kotlin

targetSdk : 31

minSdk : 23

---------------------------------

 

이번 포스팅은 

OKHttp Logging Interceptor를 사용하여 Http 통신 로그를 기록하는 방법 관련입니다.

 

 

먼저 okHttp3을 사용하기 위해 Gradle Dependencis에 아래 빌드 종속 항목 중 okhttp 관련 종속성을 추가해주세요.

 

implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.google.code.gson:gson:2.8.9'
implementation 'com.squareup.okhttp3:okhttp:4.9.1'
implementation 'com.squareup.okhttp3:logging-interceptor:4.8.0'
implementation "com.squareup.okhttp3:okhttp-urlconnection:4.9.1"
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

 

 

HttpLoggingInterceptor는 요청 또는 응답 정보를 기록하는 OkHttp의 인터셉터입니다. 

아래와 같이 HttpLoggingInterceptor 객체를 생성하고  HttpLoggingInterceptor의 level을 설정해줍니다.

val httpLoggingInterceptor = HttpLoggingInterceptor()
httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY

 

그리고 okhttp client를 생성해줍니다.

 

val client = OkHttpClient.Builder()
    .sslSocketFactory(sslSocketFactory, trustAllCerts[0] as X509TrustManager)
    .hostnameVerifier { hostname, session -> true }
    .addInterceptor(headerInterceptor)
    .addInterceptor(httpLoggingInterceptor)
    .connectTimeout(60, TimeUnit.SECONDS)
    .readTimeout(60, TimeUnit.SECONDS)
    .writeTimeout(60, TimeUnit.SECONDS)
    .build()

 

client에 

.addInterceptor(httpLoggingInterceptor)

위 소스를 추가하여 okttp client에 httpLoggingInterceptor를 셋팅해줍니다.

 

 

HttpLoggingInterceptor의 level은 속성입니다.

 

 

logcat에 "OkHttp"를 검색하면 통신 기록들을 확인할 수 있습니다.

 

-----------------------------------------

 

 

++ 인터셉터를 사용하여 통신 규격 헤더에 값을 추가할 수 있습니다. 저는 Custom한 UserAgent를 추가했습니다.

val headerInterceptor = Interceptor {
    val request = it.request()
        .newBuilder()
        .addHeader("User-Agent", USER_AGENT)
        .build()
    return@Interceptor it.proceed(request)
}
반응형

댓글