Retrofit을 Coroutine으로 비동기적으로 사용해서 서버와 데이터 주고받기 실습
class RetrofitCoroutineActivity : AppCompatActivity() {
private lateinit var binding: ActivityRetrofitCoroutineBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityRetrofitCoroutineBinding.inflate(layoutInflater)
setContentView(binding.root)
val retrofit = Retrofit.Builder()
.baseUrl("https://jsonplaceholder.typicode.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
val service = retrofit.create(RetrofitService2::class.java)
val job = runBlocking {
val response = service.getPersonList()
if (response.isSuccessful) {
Log.e("retrofitTest", response.body()!![0].title.toString())
}
}
val job2 = runBlocking {
val person = Person(100, "test3", "body3")
val response = service.postPersonList(person)
if (response.isSuccessful) {
Log.e("retrofitTest", response.body()!!.title.toString())
}
}
}
}
interface RetrofitService2 {
@GET("posts")
suspend fun getPersonList(): Response<ArrayList<Person>>
@POST("posts")
suspend fun postPersonList(
@Body person: Person
): Response<Person>
}
class Person (
var userId : Int?= null,
var title : String? = null,
var body : String? = null
):Serializable{
constructor(id: Int) : this()
}