Using Ktor in Android application

Tuong, Nguyen Thanh (aka Alan)
2 min readSep 21, 2020

--

Photo by Ken Suarez on Unsplash

What Is Ktor?

From official website: “Ktor is a framework to easily build connected applications — web applications, HTTP services, mobile and browser applications. Modern connected applications need to be asynchronous to provide the best experience to users, and Kotlin coroutines provide awesome facilities to do it in an easy and straightforward way.”

It supports multiplatform projects. This article explores how to implement the framework in Android project.

Implementation

def ktor_version = '1.3.0'

implementation "io.ktor:ktor-client-android:$ktor_version"
// in your code, create the client
// HttpClient(Android)

implementation "io.ktor:ktor-client-okhttp:$ktor_version"
// in your code, create the client
// HttpClient(Okhttp)

implementation "io.ktor:ktor-client-cio:$ktor_version"
// in your code, create the client
// HttpClient(CIO)

implementation "io.ktor:ktor-client-serialization-jvm:$ktor_version"

Building the client

“Ktor HTTP Client has a common interface but allows to specify an engine that processes the network request. Different engines have different configurations, dependencies and supporting features.”
For Android, you can work with one of the following engines:

CIO
CIO (Coroutine-based I/O) is a Ktor implementation with no additional dependencies and is fully asynchronous. It only supports HTTP/1.x for now. CIO provides maxConnectionsCount and a endpointConfig for configuring.

OkHttp
There is a engine based on OkHttp

Android
The Android engine doesn’t have additional dependencies and uses a ThreadPool with a normal HttpURLConnection, to perform the requests.

For example, we use KotlinxSerializer to parse the JSON response (or other libraries like Gson, Jackson, etc).

// You can replace CIO with your engine of choice
private val client = HttpClient(CIO) {
install(JsonFeature) {
serializer = KotlinxSerializer(Json.nonstrict)
}
}

Making Requests

To make a GET/POST request, we have to use the get/post suspend function with a response data class and request URL.

client.get<ContactResult>("https://randomuser.me/api/?results=25")

Headers

To add headers into Ktor request, you can do:

client.get<ContactResult>("https://randomuser.me/api/?results=25") {
headers
{
append("custom-header", "header-value")
}
}

You can take a look at sample on my github:
https://github.com/alanrb/Ktor-Android-example

Thanks for reading!

--

--

Responses (1)