깨알 개념/Android

[Android] Retrofit - Logging, Timeout 관리 (Interceptor)

interfacer_han 2024. 6. 11. 15:37

#1 이전 글

 

[Android] Retrofit - 기초

#1 이전 글 [Android] Retrofit - 배경과 구조#1 Restrofit의 배경#1-1 REST API REST API (REpresentational State Transfer Application Programming Interface)#1 무엇(What)에 대한 API인가?#1-1 개요REST(REpresentational State Transfer) 또는

kenel.tistory.com

위 게시글의 완성된 앱을 일부 수정해서, Retrofit Instance가 통신 기록(Log)을 남기게 만든다. 또, Retrofit Instance가 서버-클라이언트 간 통신을 성공 또는 실패(Timeout)로 판단하는 규칙을 바꿔본다.

 

#2 Interceptor

 

Interceptors - OkHttp

Interceptors Interceptors are a powerful mechanism that can monitor, rewrite, and retry calls. Here’s a simple interceptor that logs the outgoing request and the incoming response. class LoggingInterceptor implements Interceptor { @Override public Respon

square.github.io

Retrofit은 OkHttp 기반이다. 그리고 OkHttp 클라이언트(모듈)에는 Interceptor를 달 수 있다. 이 Interceptor의 역할은 서버-클라이언트 간 Request 및 Response를 모니터링이다.

 

#3 코드 수정

#3-1 모듈 수준 build.gradle 수정

plugins {
    ...
}

android {
    ...
}

dependencies {

    ...

    // Retrofit
    ...

    // Coroutines
    ...

    // ViewModel, LiveData
    ...

    // OKHttp
    implementation("com.squareup.okhttp3:logging-interceptor:5.0.0-alpha.6")
}

모듈 수준 build.gradle의 dependencies { ... }에 Interceptor를 추가한다.

 

#3-2 RetrofitInstance.kt 수정

// package com.example.loggingandtimeoutmanagement

import com.google.gson.GsonBuilder
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

class RetrofitInstance {
    companion object {
        val BASE_URL = "https://jsonplaceholder.typicode.com/"

        val interceptor = HttpLoggingInterceptor().apply {
            this.level = HttpLoggingInterceptor.Level.BODY // 요청(Request) 및 응답(Response)의 모든 본문(Body) 내용을 로그로 기록하겠다는 설정
        }

        val client = OkHttpClient.Builder().apply {
            this.addInterceptor(interceptor)
                .connectTimeout(30, TimeUnit.SECONDS) // 30초간 서버와의 통신(연결상태 확인)을 시도, 30초 초과 시 통신 실패로 간주
                .readTimeout(20, TimeUnit.SECONDS) // 서버가 클라이언트에게 보내오는 데이터 패킷(단위) 간 도착 시간이 20초를 초과하면 통신 실패로 간주 (Response 받기를 포기)
                .writeTimeout(25, TimeUnit.SECONDS) // 클라이언트가 서버로 보내주는 패킷 간 도착 시간이 25초를 초과하면 통신 실패로 간주 (Response 받기를 포기)
        }.build()

        fun getRetrofitInstance(): Retrofit {
            return Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(GsonBuilder().create()))
                .build()
        }
    }
}

이와 같이 코드를 수정하면 된다. 먼저, HttpLogginInterceptor()로 인터셉터 객체를 만들고, 이 인터셉터가 통신(Request 및 Response)의 모든 본문(Body)를 기록하게 설정한다. 그리고 OkHttpClient에 이 인터셉터를 달아준다.

 

Client에 인터셉터를 다는 것과 독립적으로, Client에는 connectTimeout, readTimeout, writeTimeout도 설정해줄 수 있다. Timeout에 대한 자세한 정보는 여기서 확인한다. Timeout은 기본값이 이미 존재하며, 위 코드처럼 사용자 정의할 일은 거의 없다고 한다. 하지만, 인터넷 속도가 굉장히 느려 Timeout을 넓게 잡아줄 필요가 있는 상황이라면 적절히 넓혀줄 필요가 생긴다. 반대 극단으로 Timeout을 아주 넓게 잡아버리면, 사실상 통신 불능인 상황임에도 오지 않을 데이터 패킷을 계속 기다리며 대기하는 불상사가 발생할 수 있으니 주의해야 한다.

 

#4 작동 확인

위 스크린샷과 같이 OkHttp의 통신 로그를 확인할 수 있다.

#5 완성된 앱

 

android-practice/retrofit/LoggingAndTimeoutManagement at master · Kanmanemone/android-practice

Contribute to Kanmanemone/android-practice development by creating an account on GitHub.

github.com

'깨알 개념 > Android' 카테고리의 다른 글

[Android] Notifications - 기초  (0) 2024.06.12
[Android] Retrofit - Post  (0) 2024.06.11
[Android] Retrofit - MVVM 구조  (0) 2024.06.05
[Android] Retrofit - 기초  (0) 2024.05.29
[Android] Retrofit - 배경과 구조  (0) 2024.05.28