레트로핏이란 안드로이드에서 REST API통신을 지원하기 위한 라이브러리이다.
현재 안드로이드에서 HTTP 통신 라이브러리 중 가장 많이 사용된다.
빠르다: AsyncTask가 없어서 빠르다고 한다.
구현이 편하다: 대부분의 반복적인 구현을 라이브러리에서 해주기 때문에 구현이 쉽다.
가독성이 좋다: Annotation의 사용으로 어떤 역할을 하는지 한눈에 알 수 있다.
1.1. manifest에서 인터넷 권한 설정하기.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.networkprac2">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.NetworkPrac2">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
1.2. gradle(Module)에 retrofit에 대한 의존성 추가하기.
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation "com.squareup.retrofit2:converter-moshi:2.9.0" //json을 파싱해주는 moshi 라이브러리
2.1. 데이터가 어떻게 이루어졌는지 확인하고 그에 맞는 클래스 생성.
아래 예제에서 사용한 데이터: https://kobis.or.kr/kobisopenapi/webservice/rest/boxoffice/searchDailyBoxOfficeList.json?key=f5eef3421c602c6cb7ea224104795888&targetDt=20220311
data class Result(
val boxOfficeResult: BoxOfficeResult)
@JsonClass(generateAdapter = true)
data class BoxOfficeResult(
val boxofficeType: String,
val showRange: String,
val dailyBoxOfficeList: List<DailyBoxOfficeList>
)
@JsonClass(generateAdapter = true)
data class DailyBoxOfficeList(
val rnum: String,
val rank: String,
val movieNm: String,
val audiCnt: String,
val audiAcc: String
)
3.1. 서버에게 요청할 행동을 정의하는 인터페이스를 만들기. 여기서는 단순히 데이터를 요청해서 받아오는 메서드만 정의했다.
interface MovieApiService {
@GET("/kobisopenapi/webservice/rest/boxoffice/searchDailyBoxOfficeList.json")
suspend fun getProperties(
@Query("key") key: String,
@Query("targetDt") targetDt: String
): Result
}
private const val BASE_URL = "https://www.kobis.or.kr"
private val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
private val retrofit = Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create(moshi))
.baseUrl(BASE_URL)
.build()
interface MovieApiService {
@GET("/kobisopenapi/webservice/rest/boxoffice/searchDailyBoxOfficeList.json")
suspend fun getProperties(
@Query("key") key: String,
@Query("targetDt") targetDt: String
): Result
}
object MovieApi {
val movieService: MovieApiService by lazy {
retrofit.create(MovieApiService::class.java)
}
}
사용할 때는 MovieApi 객체에 접근해서 미리 만들어둔 인터페이스의 메서드를 사용하면 된다.
private fun getMovieProperties(date: String) {
val key = "c3c3c19c98650f46d506e0f334259831"
val date = "20220311"
viewModelScope.launch {
try {
_property.value = MovieApi.movieService.getProperties(key, date).boxOfficeResult.dailyBoxOfficeList
_response.value = "data accept ${property.value!!.size}."
Log.i("Result", "try ${_response.value}")
} catch (e: Exception) {
Log.i("Result", "catch ${e.message}")
_response.value = "Failure " + e.message
}
}
}
글라이드는 구글에서 제공하는 이미지를 빠르고 효율적으로 불러올 수 있게 도와주는 라이브러리이다. Glide는 어떠한 종류의 이미지이더라도 빠르고 부드럽게 스크롤 하는 것을 목적으로 한다. (동영상과 gif도 지원한다.)
implementation 'com.github.bumptech.glide:glide:4.13.0'
kapt 'com.github.bumptech.glide:compiler:4.13.0'
Glide.with(context)
.load("URL")
... // 기타 다양한 함수들..
.into(imageView)
이미지가 로딩되는 중에 보여질 이미지를 설정한다.
Glide.with(context)
.load("URL")
.placeholder(image)
.into(imageView)
이미지를 불러오지 못할때 보여질 이미지를 설정한다.
Glide.with(context)
.load("URL")
.error(image)
.into(imageView)