Hanbit the Developer

[Kotlin] Send Get-Request to api server And Get Response Using retrofit2 본문

Mobile/Android

[Kotlin] Send Get-Request to api server And Get Response Using retrofit2

hanbikan 2021. 5. 28. 23:24

0. build.gradle

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

저장 후 'Sync Project With Gradle Files'는 필수이다.

 

 

1. Interface 및 데이터 형식 지정

 

MyApi.kt

import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Header
import retrofit2.http.Query

interface MyApi {
    @GET("ex/api.json")
    fun getSearchKeyword(
        @Header("h1") h1: String,
        @Query("q1") q1: String,
        @Query("q2") q2: String
    ): Call<Documents>
}

// 지정된 데이터셋
data class Documents(
    var documents: List<Place>
)

data class Place(
    var id: String
)

 

2. retrofit2

import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

// ... In some class
private fun sendGetRequest(){
        // Retrofit 구성
        val retrofit = Retrofit.Builder()
            .baseUrl("https://ex.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()
        val api = retrofit.create(MyApi::class.java)
        
        // GET 요청
        try{
            val call = api.getSearchKeyword("h1", "q1", "q2")

            call.enqueue(object: Callback<Documents> {
                override fun onResponse(
                    call: Call<Documents>,
                    response: Response<Documents>
                ) {
                    Log.i("성공", response.body().toString())
                }

                override fun onFailure(call: Call<Documents>, t: Throwable) {
                    Log.i("MainActivity", "Failed To Get Request: ${t.message}")
                }

            })
        }catch(e: Exception){
            Log.e("MainActivity", e.stackTrace.toString())
        }
    }