Retrofit은 서버와 클라이언트 간 http 통신을 위한 라이브러리이다. REST 기반의 웹 서비스를 통해 JSON 구조의 데이터를 쉽게 가져오고 업로드할 수 있다.
1. 의존성 추가
// Retrofit 라이브러리
implementation "com.squareup.retrofit2:retrofit:2.9.0"
// Gson 변환기 라이브러리
implementation "com.squareup.retrofit2:converter-gson:2.9.0"
2. 인터넷 퍼미션 허용
<uses-permission android:name="android.permission.INTERNET"/>
만약, http로 시작하는 사이트에 접근한다면 아래와 같이 추가해준다.
<application
android:usesCleartextTraffic="true">
3. data class 생성
: JSON Object의 파싱을 위해 사용
: Response와 Request Body를 관리하는 Model Class
@Parcelize
data class Book(
@SerializedName("isbn") val id: String,
@SerializedName("title") val title: String,
@SerializedName("description") val description: String,
@SerializedName("price") val priceSales: String,
@SerializedName("image") val coverSmallUrl: String,
@SerializedName("link") val mobileLink: String
): Parcelable
JSON에 정해져 있는 이름을 사용하지 않고 따로 변수명을 사용하고 싶다면 @SerializedName
어노테이션을 붙이고 ("")에 원래 변수명을 넣어주고 그 밑에 사용할 변수명을 선언해주면 된다.
4. 인터페이스 정의
: 사용할 HTTP Method를 정의해놓은 Interface
: POST / GET / PUT / DELETE
interface BookAPI {
@GET("/v1/search/book.json")
fun getBooksByName(
@Header("X-Naver-Client-Id") id: String,
@Header("X-Naver-Client-Secret") secretKey: String,
@Query("query") keyword: String
): Call<SearchBooksDto>
}
5. Retrofit 객체 생성
: Interface를 사용할 객체 정의 class
: baseURL과 Converter 설정
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
// 데이터 통신을 위해 서비스를 retrofit에 연결
service = retrofit.create(BookAPI::class.java)
5. HTTP 요청과 응답
service.getBestSeller(getString(R.string.interpark_apikey))
.enqueue(object: Callback<BestSellerDto> {
override fun onFailure(call: Call<BestSellerDto>, t: Throwable) {
}
override fun onResponse(call: Call<BestSellerDto>, response: Response<BestSellerDto>) {
if (response.isSuccessful.not()) {
return
}
response.body()?.let {
adapter.submitList(it.books)
}
}
})
참고