[kotlin] 코틀린에서 Retrofit 라이브러리 연동하기

Retrofit은 안드로이드 앱에서 API 통신을 간편하게 처리할 수 있는 라이브러리입니다. 이번에는 코틀린에서 Retrofit을 사용하는 방법에 대해 알아보겠습니다.

Retrofit 라이브러리 추가

먼저, build.gradle 파일에 Retrofit 의존성을 추가해야 합니다. 아래 코드를 dependencies 블록에 추가해주세요.

implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

위의 코드는 Retrofit의 라이브러리와 Gson을 사용하여 JSON 데이터를 자바 객체로 변환하는 라이브러리를 추가하는 것입니다.

API 인터페이스 정의하기

다음으로, API 인터페이스를 정의해야 합니다. 이 인터페이스는 서버로부터 데이터를 요청하는 메소드를 포함하고 있습니다. 예를 들어, 아래와 같이 ApiService.kt 파일을 생성하고 다음 코드를 작성해주세요.

interface ApiService {
    @GET("users")
    fun getUsers(): Call<List<User>>
}

위의 코드는 서버의 /users 엔드포인트에 GET 요청을 보내는 getUsers() 메소드를 정의한 것입니다. User 클래스는 서버의 응답 데이터를 매핑할 자바 객체입니다.

Retrofit 객체 생성하기

다음으로, Retrofit 객체를 생성해야 합니다. 이 객체는 서버의 기본 URL과 API 인터페이스를 연결해주는 역할을 합니다. 아래와 같이 ApiClient.kt 파일을 생성하고 다음 코드를 작성해주세요.

object ApiClient {
    private const val BASE_URL = "https://api.example.com/"

    val apiService: ApiService by lazy {
        val retrofit = Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    
        retrofit.create(ApiService::class.java)
    }
}

위의 코드에서 BASE_URL은 서버의 기본 URL을 나타냅니다. apiService는 Retrofit 객체를 생성하고 API 인터페이스를 구현한 객체를 반환하는 것입니다.

API 호출하기

이제 API를 호출하는 방법을 알아보겠습니다. 다음은 MainActivity.kt 파일에서 Retrofit을 사용하여 API를 호출하는 예제입니다.

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        val apiService = ApiClient.apiService
        val call = apiService.getUsers()
        
        call.enqueue(object : Callback<List<User>> {
            override fun onResponse(call: Call<List<User>>, response: Response<List<User>>) {
                if (response.isSuccessful) {
                    val users = response.body()
                    // 데이터 처리 로직 구현
                } else {
                    // 실패 처리 로직 구현
                }
            }

            override fun onFailure(call: Call<List<User>>, t: Throwable) {
                // 에러 처리 로직 구현
            }
        })
    }
}

위의 코드에서 ApiClient.apiService를 호출하여 API 인터페이스를 구현한 객체를 얻고, 해당 객체의 메소드를 호출하여 API를 실행합니다. enqueue() 메소드는 비동기로 API를 호출하고 응답을 받는 메소드입니다.

이제 Retrofit을 사용하여 코틀린에서 API를 호출하는 방법에 대해 알아보았습니다. Retrofit을 사용하면 간편하게 서버와 통신하는 코드를 작성할 수 있습니다. 자세한 내용은 Retrofit 공식 문서를 참고하시기 바랍니다.