Ktor - Client

  • Introduction

    Amper

    To use Ktor Client in your project, you need to include the appropriate dependencies in your module.yaml file:

    module.yaml

    Client

    Create a client application

    import io.ktor.client.*
    import io.ktor.client.engine.cio.*
    import io.ktor.client.request.*
    import io.ktor.client.statement.*
    suspend fun main() {
    val client = HttpClient(CIO)
    val response: HttpResponse = client.get("https://ktor.io/")
    println(response.status)
    client.close()
    }

    In Ktor, a client is represented by the HttpClient class.

    Use the HttpClient.get() method to make a GET request.

    A response will be received as a HttpResponse class object.

    Content negotiation and serialization

    src/main.kt

    ContentNegotiation

    The ContentNegotiation plugin serves two primary purposes:

    • Negotiating media types between the client and server. For this, it uses the Accept and Content-Type headers.

    • Serializing/deserializing the content in a specific format when sending requests and receiving responses. Ktor supports the following formats out-of-the-box: JSON, XML, CBOR, and ProtoBuf.

    To use ContentNegotiation, you need to include the ktor-client-content-negotiation artifact in the build script:

    io.ktor:ktor-client-content-negotiation:$ktor_version

    Note that serializers for specific formats require additional artifacts. For example, kotlinx.serialization requires the ktor-serialization-kotlinx-json dependency for JSON. Depending on the included artifacts, Ktor chooses a default serializer automatically. If required, you can specify the serializer explicitly and configure it.

    (keep reading) Serialitzation