Make a GET Request in Kotlin
Perform an HTTP GET on Android using the OkHttp client with a coroutine.
Also known as: OkHttp GET Kotlin, Kotlin HTTP request
intermediate
OkHttp is the standard HTTP client on Android. Wrap its blocking execute() in Dispatchers.IO so the network call runs off the main thread.
What it is
OkHttp is the de-facto HTTP client on Android and underpins Retrofit. You build a Request, hand it to a shared OkHttpClient, and read the response body. The synchronous execute() call blocks, so run it inside withContext(Dispatchers.IO) from a coroutine to keep the main thread responsive.
Create one OkHttpClient for the whole app and reuse it — it pools connections and threads. Always close the response body (Kotlin's use {} does this) to avoid leaking connections.
Worked example
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
val client = OkHttpClient()
suspend fun fetch(url: String): String = withContext(Dispatchers.IO) {
val request = Request.Builder().url(url).build()
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) error("HTTP ${response.code}")
response.body?.string() ?: ""
}
}
Failure mode — when it misleads
Calling execute() on the main thread throws NetworkOnMainThreadException on Android; always dispatch to Dispatchers.IO. Reading response.body?.string() twice throws, because the stream is consumed once — capture it in a variable if you need it more than once.
Related entries
Sources & further reading
- OkHttp (article)