본문 바로가기
Android

[안드로이드] Retrofit 사용시 HTTP통신 Error 확인방법

by JongSeok 2023. 3. 1.

안드로이드에서는 서버와 편리한 API 통신을 위해 Retrofit을 제공합니다.

Retrofit을 이용해 서버로 데이터를 요청하고 응답을 받는 과정에서 다양한 HTTP Error나 Exception이 발생할 수 있습니다.

 

직접 어느 부분에서 문제가 있는지 찾으려면 까다롭기 때문에 통신 과정의 정보를 얻어야 하는데 이때 사용하는 것이 HttpLoggingInterceptor입니다.

 

HttpLoggingInterceptor을 사용하면 요청 시점부터 응답까지 많은 통신 정보를 로그를 통해 기록할 수 있어 어디서 어떤 오류가 발생하는지 쉽게 확인이 가능합니다.

통신 로그 예시


사용법

build.gradle 

dependencies {
    ...
    implementation 'com.squareup.okhttp3:okhttp:4.10.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:4.10.0'
}

먼저 app수준 build.gradle에 의존성을 추가합니다.

RetrofitInstance

private val okHttpClient: OkHttpClient by lazy {
    val httpLoggingInterceptor = HttpLoggingInterceptor()
        .setLevel(HttpLoggingInterceptor.Level.BODY)
    OkHttpClient.Builder()
        .addInterceptor(httpLoggingInterceptor)
        .build()
}

private val retrofit: Retrofit by lazy {
    Retrofit.Builder()
        .addConverterFactory(GsonConverterFactory.create())
        .baseUrl(BASE_URL)
        .client(okHttpClient)
        .build()
}

Retrofit 객체를 생성하기 이전에 OkHttpClient 객체를 먼저 생성합니다.

OkHttpClient를 build하는 과정에서 Logcat에 로그를 남길 수 있도록 addInterceptor(httpLoggingInterceptor) 구문을 추가해 줍니다.

그리고 Retrofit 객체를 build할 때 client에 위에서 생성했던 okHttpClient를 등록합니다.

 

이제 Logcat에서 Http 통신 결과를 위의 예시처럼 확인할 수 있습니다.

 

다음 포스팅에서는 Http 통신의 결과로 상태코드가 반환되는데 이때 반환되는 상태코드가 어떤 의미를 내포하고 있는지에 대해 작성하겠습니다 :)

728x90
반응형