안드로이드

(Android) Retrofit2 를 이용한 Http request (Json)

danune.dev 2022. 6. 13. 10:56

서버에 Get request로 User 리스트를 받는 예제입니다

(서버는 미리 구현되어있다고 가정)

0. 사전 정의 

  • API 호출 주소: http://localhost/api/getUsers
  • 응답 예제
[
    {
    	"name": "aaa",
        "age": 12,
        "addr": "addr1"
    },
    {
    	"name": "bbb",
        "age": 14,
        "addr": "addr2"
    },
    {
    	"name": "ccc",
        "age": 13,
        "addr": "addr3"
    }
]

 

 

1. 의존성 추가 (app/build.gradle)

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

 

2. dto 정의 (주고받을 데이터 타입)

data class User(
    val name: String,
    val age: Int,
    @SerializeName("addr") // 내려받는 json의 이름과 코드에서의 이름을 다르게 사용하려면
    val address: String
)

 

3. API interface 정의

interface Api {
    @GET("userList")
    fun getUserList(
        @Query("name")
        name: String? = null,
    ): Call<List<User>>
}

 

4. retrofit 초기화

val client = OkHttpClient().newBuilder().build()
val retrofit = Retrofit.Builder()
    .baseUrl(http://localhost/api/)
    .client(client)
    .addConverterFactory(GsonConverterFactory.create())
    .build()
val api = retrofit.create(Api::class.java)

 

5. userList 요청

api.getUsers().enqueue(
    object: Callback<List<User>> {
        override fun onResponse(call: Call<List<User>>, response: Response<List<User>>) {
        	// response 처리
        }

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