[Android] Retrofit2 사용해보기
Android Http 개발에 많이 쓰이는 Retrofit2을 사용해보겠습니다.
먼저 AndroidManifest.xml 에 Internet 권한을 추가합니다.
<uses-permission android:name="android.permission.INTERNET" />
다음으로 build.gradle (Module: app) 파일에 dependency를 추가해줍니다.
compile 'com.squareup.retrofit2:retrofit:2.4.0'
compile 'com.squareup.retrofit2:converter-gson:2.4.0'
RetrofitClient Class와 RetrofitService Interface를 만들겠습니다.
RetrofitClient에는 static method로 Client의 Instance를 생성해주고
Http Request를 하게될 BaseUrl을 명시하며 RetrofitService를 return 하여
Activity나 Fragment에서 Http Request을 할 수 있게 합니다.
RetrofitService는 API 선언을 할 Interface 입니다.
간략한 소스로 보겠습니다.
RetrofitClient.kt
class RetrofitClient {
companion object {
private val retrofitClient: RetrofitClient = RetrofitClient()
fun getInstance(): RetrofitClient {
return retrofitClient
}
}
fun buildRetrofit(): RetrofitService {
val retrofit: Retrofit? = Retrofit.Builder()
.baseUrl("http://yongyi1587.tistory.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
val service: RetrofitService = retrofit!!.create(RetrofitService :: class.java)
return service
}
}
RetrofitService.kr (Interface)
@GET("30")
fun read(@Path("no") no: String)
: Call<JsonObject>
위 처럼 API를 선언하고 http request시 JsonObject를 받아오게 됩니다.
retrofit github에 있는 예제들은 github에서 repo의 정보를 가져오는 것을 테스트 해볼 수 있습니다.
http://square.github.io/retrofit/ <- Retrofit Github 주소