Before 2022/Android

Kotlin + Retrofit2 + Okhttp3을 활용한 REST API 기본 메소드 작성

Eljoe 2020. 7. 16. 15:00

Manifest

<uses-permission android:name="android.permission.INTERNET"/>

 

build.gradle(app)에 아래와 같은 내용 추가 (*1.8 관련 내용 추가 안할 시, NoSuchMethodError 발생)

android {
    ...
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = "1.8"
    }
    ...
}

dependencies {
    ...
    //Retrofit2
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    
    //Okhttp3
    implementation 'com.squareup.okhttp3:okhttp:4.8.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:4.8.0'
    ...
}
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import java.util.concurrent.TimeUnit

interface ApiService {

    @GET
    fun findListAll(): Call<List<Model>>

    companion object {
        private const val BASE_URL = "Your_Base_URL"
        private const val CONNECT_TIMEOUT_SEC = 20000L

        fun create(): ApiService {
            val interceptor = HttpLoggingInterceptor()
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY)

            val client = OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .connectTimeout(CONNECT_TIMEOUT_SEC, TimeUnit.SECONDS)
                .build()

            val retrofit = Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build()

            return retrofit.create(ApiService::class.java)
        }
    }
}