OkHttp 라이브러리를 코루틴을 이용해서 비동기적으로 실행하기 실습
참고 - 센치한개발자
class OkHttpCorutineActivity : AppCompatActivity() {
private lateinit var binding: ActivityOkHttpCorutineBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityOkHttpCorutineBinding.inflate(layoutInflater)
setContentView(binding.root)
coroutine()
}
fun coroutine() {
CoroutineScope(Dispatchers.Main).launch {
val html = CoroutineScope(Dispatchers.IO).async {
getHtml()
}.await()
binding.txt.text = html
}
}
fun getHtml(): String {
val clinet = OkHttpClient.Builder().build()
val req = Request.Builder().url("https://www.google.com").build()
clinet.newCall(req).execute().use { response ->
return if (response.body != null) {
response.body!!.toString()
} else {
"body is null"
}
}
}
fun getHtmlStr() {
val clinet = OkHttpClient.Builder().build()
val req = Request.Builder().url("https://www.google.com").build()
clinet.newCall(req).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
TODO("Not yet implemented")
}
override fun onResponse(call: Call, response: Response) {
CoroutineScope(Dispatchers.Main).launch {
binding.txt.text = response.body!!.toString()
}
}
})
}
}
//OkHttpCorutineActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".OkHttpCorutineActivity">
<TextView
android:id="@+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>```