티스토리 뷰
서버에 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) {
// 에러 처리
}
}
)
'안드로이드' 카테고리의 다른 글
(Android) Map Intent 사용하기 (네이버 지도에서 주소표시 등) (0) | 2022.06.14 |
---|---|
(Android) Recyclerview 에서 item간 일정한 간격 주는 방법 (0) | 2022.06.13 |
(Android) EditText data binding (0) | 2022.06.10 |
(Android) Roboto 폰트 적용 (0) | 2022.06.10 |
(Android) night theme 적용하기 (0) | 2022.06.09 |
댓글
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday