Skip to content

OkHttp

implementation("com.squareup.okhttp3:okhttp:4.9.3")
val client = OkHttpClient()

Use withContext(Dispatchers.IO) to perform the request in background

val request = Request.Builder().url("<url>").build()
val response = client.newCall(request).execute()
val body = call.body?.string()?: return@withContext emptyList<MusicList>()
val gson = Gson()
val listType = object : TypeToken<List<MusicList>>() {}.type
gson.fromJson(res, listType)
var data by remember { mutableStateOf<List<Music>>(emptyList()) }
withContext(Dispatchers.IO) {
val client = OkHttpClient()
val request = Request.Builder()
.url("https://skills-music-api.eliaschen.dev/music")
.build()
data = client.newCall(request).execute().use { response ->
Gson().fromJson(response.body?.string(), object : TypeToken<List<Music>>() {}.type)
}
}
data class MusicList(
val title: String,
val url: String
)
val gson = Gson()
val client = OkHttpClient()
suspend fun fetchUrl(): List<MusicList> {
return withContext(Dispatchers.IO) {
try {
val request = Request.Builder().url("$host/music").build()
val call = client.newCall(request).execute()
if (call.isSuccessful) {
val res = call.body?.string() ?: return@withContext emptyList<MusicList>()
val listType = object : TypeToken<List<MusicList>>() {}.type
gson.fromJson(res, listType)
} else {
emptyList<MusicList>()
}
} catch (e: Exception) {
emptyList<MusicList>()
}
}
}