OkHttp
Dependencies
Section titled “Dependencies”implementation("com.squareup.okhttp3:okhttp:4.9.3")Basic Usage
Section titled “Basic Usage”val client = OkHttpClient()Use withContext(Dispatchers.IO) to perform the request in background
Create a request
Section titled “Create a request”val request = Request.Builder().url("<url>").build()Get the response
Section titled “Get the response”val response = client.newCall(request).execute()val body = call.body?.string()?: return@withContext emptyList<MusicList>()Parse to JSON with Gson
Section titled “Parse to JSON with Gson”val gson = Gson()val listType = object : TypeToken<List<MusicList>>() {}.typegson.fromJson(res, listType)Simple Example
Section titled “Simple Example”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) }}Example with Exception Handling
Section titled “Example with Exception Handling”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>() } }}