Skip to content

mende273/KtorAndroidClientExample

Repository files navigation

Ktor Android Http Client Example

Simple implementation of Ktor Http Client for Android with Kotlin Serialization. The project is using the free api from thecocktaildb for providing data.

What is Ktor?

Ktor is an open-source framework built by JetBrains for building asynchronous servers and clients using Kotlin programming language.

Implementation

1. build.gradle.kts(app module)

  • Add plugin id("kotlinx-serialization")
  • Add Dependencies
plugins {
   ...
    id("kotlinx-serialization")
}

implementation(platform("io.ktor:ktor-bom:2.3.12"))
implementation("io.ktor:ktor-client-android")
implementation("io.ktor:ktor-client-serialization")
implementation("io.ktor:ktor-client-logging")
implementation("io.ktor:ktor-client-content-negotiation")
implementation("io.ktor:ktor-serialization-kotlinx-json")

2. build.gradle.kts(root)

  • Add Kotlin Serialization plugin
id("org.jetbrains.kotlin.plugin.serialization") version "2.0.0"

3. Create the Http Android Client

private const val NETWORK_TIME_OUT = 6_000L

val httpClientAndroid = HttpClient(Android) {
    install(ContentNegotiation) {
        json(
            Json {
                prettyPrint = true
                isLenient = true
                useAlternativeNames = true
                ignoreUnknownKeys = true
                encodeDefaults = false
            }
        )
    }

    install(HttpTimeout) {
        requestTimeoutMillis = NETWORK_TIME_OUT
        connectTimeoutMillis = NETWORK_TIME_OUT
        socketTimeoutMillis = NETWORK_TIME_OUT
    }

    install(Logging) {
        logger = object : Logger {
            override fun log(message: String) {
                Log.v("Logger Ktor =>", message)
            }
        }
        level = LogLevel.ALL
    }

    install(ResponseObserver) {
        onResponse { response ->
            Log.d("HTTP status:", "${response.status.value}")
        }
    }

    install(DefaultRequest) {
        header(HttpHeaders.ContentType, ContentType.Application.Json)
    }

    defaultRequest {
        contentType(ContentType.Application.Json)
        accept(ContentType.Application.Json)
    }
}

Other technologies used in the project

  • Koin - Koin is a pragmatic and lightweight dependency injection framework for Kotlin developers
  • Jetpack Compose - Android’s modern toolkit for building native UI.
  • Coroutines and Flow - Official Kotlin's tooling for performing asynchronous work.
  • ViewModel - The ViewModel is designed to store and manage UI-related data in a lifecycle conscious way.
  • StateFlow - StateFlow is a state-holder observable flow that emits the current and new state updates to its collectors.

Releases

No releases published

Packages

No packages published

Languages