DBILITY

android retrofit2 본문

android

android retrofit2

DBILITY 2024. 4. 1. 14:19
반응형

https://square.github.io/retrofit/

 

Retrofit

A type-safe HTTP client for Android and Java

square.github.io

libs.versions.toml

[versions]
....
retrofit2 = "2.11.0"
kotlinx-serialization-json = "1.6.3"

[libraries]
....
retrofit2 = { group = "com.squareup.retrofit2", name = "retrofit", version.ref = "retrofit2" }
retrofit2-converter-gson = { group = "com.squareup.retrofit2", name = "converter-gson", version.ref = "retrofit2" }
retrofit2-converter-jackson = { group = "com.squareup.retrofit2", name = "converter-jackson", version.ref = "retrofit2" }
kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "kotlinx-serialization-json" }

....

build.gradle.kts(Module)

dependencies {
    ....
    implementation(libs.retrofit2)
    implementation(libs.retrofit2.converter.gson)
    implementation(libs.retrofit2.converter.jackson)
    implementation(libs.kotlinx.serialization.json)
    ....
}

data class(dto) > Service(interface) > Builder instance 순서

https://koreanjson.com/

 

Korean JSON

{ Korean JSON } Super simple JSON API in Korean. Request GET, POST, PUT, DELETE actions and get JSON data in Korean back to get the most out of the look and feel of Korean language when prototyping your project. 한국어 데이터를 제공하는 초간

koreanjson.com

위 api사이트에서 user목록을 읽어 본다.

User.kts(DTO)

package com.dbility.myretrofi

import com.fasterxml.jackson.annotation.JsonProperty
import kotlinx.serialization.Serializable

@Serializable
data class User(
    @JsonProperty("id") val id : Long,
    @JsonProperty("name") val name : String,
    @JsonProperty("username") val userName : String,
    @JsonProperty("email") val email : String,
    @JsonProperty("phone") val phone : String?,
    @JsonProperty("website") val website : String?,
    @JsonProperty("province") val province : String?,
    @JsonProperty("city") val city : String?,
    @JsonProperty("district") val district : String?,
    @JsonProperty("street") val street : String?,
    @JsonProperty("zipcode") val zipcode : String?,
    @JsonProperty("createdAt") val createdAt : String,
    @JsonProperty("updatedAt") val updatedAt : String?
)

UserService(interface)

package com.dbility.myretrofi

import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Path

interface UserService {

    @GET("users/{id}")
    fun getUsers(@Path("id") id:String): Call<List<User>>
}
package com.dbility.myretrofi

import android.os.Bundle
import android.util.Log
import android.widget.ArrayAdapter
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.dbility.myretrofi.databinding.ActivityMainBinding
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.jackson.JacksonConverterFactory

class MainActivity : AppCompatActivity() {

    companion object {
        private const val TAG: String = "MainActivity"
    }

    private val binding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }

    private val retrofit by lazy {
        Retrofit.Builder()
            .baseUrl("https://koreanjson.com/")
            .addConverterFactory(JacksonConverterFactory.create())
            .build()
    }

    private val userService by lazy {
        retrofit.create(UserService::class.java)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        with(binding) {
            activityMainButtonGet.setOnClickListener {
                userService.getUsers("").enqueue(object : Callback<List<User>> {
                    override fun onResponse(
                        call: Call<List<User>>,
                        response: Response<List<User>>
                    ) {
                        if (response.isSuccessful.not()) {
                            Log.d(TAG, "Response Failure")
                            Toast.makeText(
                                this@MainActivity,
                                "Response Failure",
                                Toast.LENGTH_SHORT
                            ).show()
                            return
                        }
                        response.body()?.let {
                            Log.d(TAG,it.toString())                            
                        } ?: run {
                            Log.d(TAG, "response body is empty")
                        }
                    }

                    override fun onFailure(call: Call<List<User>>, throwable: Throwable) {
                        Log.d(TAG, throwable.toString())
                    }
                })
            }
        }

    }
}

callback은 Main Tread에서 실행됨.

반응형

'android' 카테고리의 다른 글

android dark mode 비활성화  (0) 2024.04.04
android external library register  (0) 2024.04.02
공휴일 api 제공 site  (0) 2024.04.01
android room database  (0) 2024.03.29
android viewmodel 에서 constructor arguments  (0) 2024.03.29
Comments