Retrofit?
안드로이드에서 필요한 데이터를 서버와 주고받을 수 있도록 HTTP 통신을 돕는 Third Party Library
dependencies {
...
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.google.code.gson:gson:2.8.6'
}
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.-">
<uses-permission android:name="android.permission.INTERNET" />
...
</manifest>
object ApiClient {
private val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
val service = retrofit.create(FlatformsService::class.java)
}
interface FlatformsService {
@GET("api/v1/flatforms")
fun getFlatforms(): Call<FlatformsResponse>
}
data class FlatformsResponse(
val code: Int,
val message: String,
val data: ArrayList<Flatforms>
)
data class Flatforms(
val id: Int,
@SerializedName("title")
val flatformsName: String
)
//JSON 구조
{
"code": 200,
"message": "OK",
"data": [
{
"id": 1,
"title": "naver"
},
{
"id": 2,
"title": "daum"
}
]
}
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
loadData()
}
fun loadData() {
val service = ApiClient.service
service.getFlatforms().enqueue(object : Callback<FlatformsResponse> {
override fun onResponse(
call: Call<FlatformsResponse>,
response: Response<FlatformsResponse>
) {
if (response.isSuccessful) {
Log.d("isSuccessful", response.body().toString())
}
}
}
override fun onFailure(call: Call<FlatformsResponse>, t: Throwable) {
Log.d("onFailure", "$t")
}
})
}
}
는 이렇게..