https://kotlinlang.org logo
Docs
Join the conversationJoin Slack
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by Linen
ktor
  • b

    Benjamin Schlie

    02/05/2021, 4:08 PM
    Hi! Is it possible to run two applications on the same server with different StatusPages? I have tried adding two routes to match different hosts and add
    install(StatusPages)
    in each of them. The routes works, but not the StatusPages.
    routing {
            header(HttpHeaders.Host, "localhost:8080") {
                route("/") {
                    handle {
                        call.respondText("Hello world")
                    }
                }
                install(StatusPages) {
                    status(HttpStatusCode.NotFound) { status ->
                        call.respondText("Not found!")
                    }
                }
            }
        }
    
        routing {
            header(HttpHeaders.Host, "another-host:8080") {
                route("/") {
                    handle {
                        call.respondText("Hello another world")
                    }
                }
                install(StatusPages) {
                    status(HttpStatusCode.NotFound) { status ->
                        call.respondText("No other world found!")
                    }
                }
            }
        }
    r
    a
    +1
    7 replies · 4 participants
  • r

    rsetkus

    02/08/2021, 1:31 AM
    Hi, What is correct way of handling empty response? When executing
    PUT
    request, api returns an empty body response but all types of ktor requests have a return type. To satisfy it, have created an empty data class, however getting an error when executing such request:
    io.ktor.client.call.NoTransformationFoundException: No transformation found: class <http://io.ktor.utils.io|io.ktor.utils.io>.ByteBufferChannel (Kotlin reflection is not available) -> class xx.yy.api.NoContent (Kotlin reflection is not available)
    . I’d guess serialization process is confused when mapping an empty response to data class. Any ideas how to fix it?
    r
    2 replies · 2 participants
  • w

    why

    02/08/2021, 10:34 AM
    hi.. how can I make a get request throw
    ClientRequestException
    in my unit tests? is it possible? I’m using the MockEngine like this
    val httpClientMock = HttpClient(MockEngine) {
                HttpResponseValidator { }
                install(JsonFeature) {
                    serializer = GsonSerializer()
                }
                engine {
                    addHandler { request ->
                        val page = request.url.parameters["page"]!!.toInt()
    
                        when {
                            page < 38 -> {
                                val t = ContentType.Application.Json.toString()
                                val headers = headersOf("Content-Type" to listOf(t))
                                TextContent(reposJson, ContentType.Application.Json)
                                respond(reposJson, headers = headers)
                            }
                            else -> throw "I can't ctor the exception"
                        }
    
                    }
                }
            }
    r
    2 replies · 2 participants
  • k

    KamilH

    02/09/2021, 4:36 PM
    I’ve got a Kotlin library that uses Ktor as a http client. When I’m trying to use it in the Java (Android) project I’m getting a
    java.lang.NoClassDefFoundError: Failed resolution of: Lio/ktor/client/features/json/JsonFeature;
    exception, even though I can see that library’s pom file contains all of the required dependencies and my consuming app is downloading those dependencies. Library is working well in the Kotlin project. Do I need to add some kind of a configuration to be able to use it from Java app?
    a
    j
    +1
    19 replies · 4 participants
  • m

    Marc de Palol

    02/09/2021, 10:02 PM
    Hi, I’m trying to test some ktor client code that uses the HttpTimeout question, but it doesn’t seem possible, In my code I have a client with the HttpTimeout feature installed. When running the tests, I create an HttpClient with a MockEngine. If I try to install the HttpTimeout feature in there I get a
    Engine doesn’t support io.ktor.client.features.HttpTimeout$Feature@5c8a5ca9
    , if I don’t install it I get another error:
    Consider installing io.ktor.client.features.HttpTimeout$Feature@157a2816 feature because the request requires it to be installed
    Isn’t there any workaround?
    r
    3 replies · 2 participants
  • j

    Jawid

    02/10/2021, 3:50 PM
    Hello everyone, I am creating an Android application using KMM and want to upload an image using Ktor. But I couldn't find proper documentation or a sample code for the same. Can anyone share with me a code snippet or a sample repo, please? Thanks in advance.
    r
    1 reply · 2 participants
  • p

    pambrose

    02/10/2021, 6:05 PM
    Hello. Can anyone tell me what the HTML DSL equivalent of
    <section  data-markdown> ... </section>
    would be? In other words, how are tag attributes with no values expressed in the DSL?
    s
    t
    13 replies · 3 participants
  • h

    Hexa

    02/11/2021, 9:26 AM
    Is there a project generator for generating multi module ktor project?
    m
    1 reply · 2 participants
  • m

    Marc Knaup

    02/11/2021, 5:14 PM
    Is there a way to connect client & server test engines? So that a Ktor client with test engine executes its request on a Ktor server with test engine.
    e
    8 replies · 2 participants
  • a

    Amritansh

    02/11/2021, 6:47 PM
    Hey Guys, I have question regarding closing HttpClient in ktor. I am working on a logging library using Multiplatform which will be accessing HttpClient frequently to send data to remote server. If I close the client after each request and then create a new client for the next request will that be better over just creating a singleton client and using it for all the request?
    e
    m
    3 replies · 3 participants
  • j

    Jeff Tycz

    02/12/2021, 1:45 AM
    I am trying to make a generic http client class with single get/post/put methods that can be used anywhere in my application without having to write a specific http call method for every case. One issue I am coming up with is some calls require different headers to be sent in the request. This is the method I am currently trying to change, I set the auth header but sometimes I need additional headers and sometimes I dont need the auth header at all
    suspend inline fun <reified T> post(authKey: String, url: String, data: Any): T? {
        val response = <http://_client.post|_client.post><HttpResponse>(url) {
            header("Authorization", "Bearer $authKey")
            contentType(ContentType.Application.Json)
            body = data
        }
    
        when (response.status.value) {
            in 300..399 -> throw RedirectResponseException(response)
            in 400..499 -> throw ClientRequestException(response)
            in 500..599 -> throw ServerResponseException(response)
        }
    
        if (response.status.value >= 600) {
            throw ResponseException(response)
        }
    
        return response.receive<T>()
    }
    Is there a way to dynamically set the headers?
    t
    3 replies · 2 participants
  • p

    Paul Woitaschek

    02/13/2021, 11:40 AM
    Did someone get ktor to work on ios? For me the get call suspends just forever:
    @Test
    fun test() {
      val client = HttpClient()
      runBlocking {
        println("start")
        val result: String = client.get("<https://www.google.com/>")
        println("result=$result")
      }
    }
    I’m using
    implementation("io.ktor:ktor-client-ios:1.5.1")
    And
    org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.2-native-mt
    With the
    strictly
    block applied
    m
    l
    14 replies · 3 participants
  • n

    natario1

    02/14/2021, 1:12 PM
    Hi! 👋 I'm using ktor client for the first time. Is there any built-in tool for request throttling? I'm hitting a server that only accepts up to 3 requests per second. I'd like to suspend until the request can be executed successfully. How would you go to implement this?
    a
    2 replies · 2 participants
  • a

    alexfu

    02/14/2021, 1:39 PM
    I'm using Ktor in a multiplatform project (Android + iOS) and I'm running into an issue with iOS where exceptions are not delivered the generated callback handler (callback handler accepts both an object and error), but instead uncaught and crashes the app. This is the error message that gets printed right before the stacktrace:
    Exception doesn't match @Throws-specified class list and thus isn't propagated from Kotlin to Objective-C/Swift as NSError
    I've determined this happens because, in Kotlin, it's not required to specify if a function throws an exception. However, when targeting a native platform, if you don't specify that the function throws, those errors will be uncaught. So what I'm doing to resolve this is to add
    @Throws(Throwable::class)
    to every single API function I have. I'm wondering if there is an easier way to manage this since there's no lint type check for this (that I'm aware of), making it's easy to forget. I also feel like this may be more of a Kotlin question than a Ktor one.
    m
    1 reply · 2 participants
  • i

    iona bartishvili

    02/14/2021, 6:58 PM
    Hey ! I just started learning ktor. After reading docs and watching videos, i cant fix my problem. I have very basic project (newly created) and when i run the app, app is hosted on 8080 port, but i cant reach the site from browser. I says "This site us Unreachable". Can somebody tell me what i am missing ? See screenshot in reply section
    j
    5 replies · 2 participants
  • j

    João Eudes Lima

    02/15/2021, 1:36 AM
    Hi, Does anyone know why I receive the request twice even though I only sent it once
    j
    8 replies · 2 participants
  • n

    Nikolay Kasyanov

    02/15/2021, 8:23 AM
    Hey folks. I stumbled upon this the hard way: https://github.com/ktorio/ktor/blob/1.4.3/ktor-client/ktor-client-core/common/src/io/ktor/client/features/DefaultResponseValidation.kt. Is there a good rationale behind making ktor response exceptions essentially inaccessible from other threads on iOS?
    3 replies · 1 participant
  • p

    ptsiogas

    02/15/2021, 5:25 PM
    Hi there, I am using Ktor 1.5.0 combined with platform specific httpclients (OkHttp & Ios). I have setup the HttpResponseValidator although whenever I receive an http error like 401, instead of catching a custom throwable I made for this case, I am always getting a NoTransformationFoundException. Have you encountered anything similar?
    r
    m
    4 replies · 3 participants
  • c

    CLOVIS

    02/15/2021, 7:28 PM
    I don't understand how https://ktor.io/docs/jwt.html works: the given code (if I understand it correctly) checks that the client has a valid token (ie. signed by the server), but there is nothing on how to send a token to the client. How can the client have a valid token if the server doesn't provide any way to generate it?
    s
    3 replies · 2 participants
  • s

    smallufo

    02/15/2021, 7:37 PM
    Hi , is there something wrong with
    ktor-client-serialization
    (1.5.1) to
    kotlinx-serialization-json
    dependency ? I tried
    <dependency>
        <groupId>io.ktor</groupId>
        <artifactId>ktor-client-serialization</artifactId>
        <version>${ktor_version}</version>
    </dependency>
    but IntelliJ & maven always complains
    Cannot resolve org.jetbrains.kotlinx:kotlinx-serialization-json:1.0.1
    command line mvn complains :
    Caused by: org.eclipse.aether.resolution.DependencyResolutionException: Could not find artifact org.jetbrains.kotlinx:kotlinx-serialization-json:jar:1.0.1 in central (<https://repo.maven.apache.org/maven2>)
        at org.eclipse.aether.internal.impl.DefaultRepositorySystem.resolveDependencies (DefaultRepositorySystem.java:352)
        at org.apache.maven.project.DefaultProjectDependenciesResolver.resolve (DefaultProjectDependenciesResolver.java:202)
    And in maven center https://repo.maven.apache.org/maven2/org/jetbrains/kotlinx/kotlinx-serialization-json/1.0.1/ There is no jar file . That’s why maven complains it cannot find JAR file. KSJ is packaging in POM , not JAR https://repo.maven.apache.org/maven2/org/jetbrains/kotlinx/kotlinx-serialization-json/1.0.1/kotlinx-serialization-json-1.0.1.pom
    <packaging>pom</packaging>
    Is it OK to import it like this ? https://repo1.maven.org/maven2/io/ktor/ktor-client-serialization/1.5.1/ktor-client-serialization-1.5.1.pom
    <dependency>
    <groupId>org.jetbrains.kotlinx</groupId>
    <artifactId>kotlinx-serialization-json</artifactId>
    <version>1.0.1</version>
    <scope>compile</scope>
    </dependency>
    Sorry not sure about this. but it seems not working. Is it maven center’s problem ?
    j
    3 replies · 2 participants
  • a

    Anders Sveen

    02/16/2021, 10:22 AM
    How can I get logging dispatched from the response in KTor Client to respect the MDC entries I get in all other log entries? I have been digging around for hours, but almost losing my mind... 🙂 I have looked for ways to set the coroutineContext for the HttpClitent etc. but I am getting lost in code. 😉 Any pointers or solutions is much appreciated. 🙂
    👀 1
    o
    5 replies · 2 participants
  • j

    Jawid

    02/16/2021, 1:54 PM
    Hi everyone, I am using Ktor 1.5.0 to upload an image to server in a KMM project, I am passing the image as a byteArray but I am getting a bad request response, here is the code:
    client.submitFormWithBinaryData<FaceResponse> {
        method = <http://HttpMethod.Post|HttpMethod.Post>
        url(IMAGE_URL)
        headers {
            this["x-api-key"] = "my_api_key_here"
        }
        parameter(
            "mode", "request_mode"
        )
        body = MultiPartFormDataContent(formData {
            append("image", request.image)
        })
    }
    Does anyone know what is the issue? Thanks
    e
    1 reply · 2 participants
  • r

    rsetkus

    02/16/2021, 2:19 PM
    Hi. Is there any way I could mock long running request using MockEngine? Writing a test where I want to test how my code performs at cancellation.
    e
    4 replies · 2 participants
  • s

    Satyam Agarwal

    02/16/2021, 3:10 PM
    Hey @e5l can you help me with this please https://github.com/ktorio/ktor/pull/2319
    e
    1 reply · 2 participants
  • p

    Paul Woitaschek

    02/17/2021, 9:56 AM
    Does ktor work on watchos? https://github.com/ktorio/ktor/issues/1378 The last comment is indicating that it doesnt
    j
    t
    7 replies · 3 participants
  • p

    Paul Griffith

    02/17/2021, 6:51 PM
    Is there a more idiomatic way to have a wrapper around an HttpClient that sets up some default features, but also allows some use-site customization? More in a thread, but basically I want to be able to create an
    XClient
    which might be backed by a
    CIOEngine
    ...but also be able to use the same class but with a
    MockEngine
    , which requires being able to add handlers
    6 replies · 1 participant
  • a

    Anders Sveen

    02/18/2021, 1:52 PM
    Can I add an
    ContinuationInterceptor
    to KTor Server execution context? I am trying to add one just by doing
    GlobalScope.embeddedServer(factory = Jetty, ... , parentCoroutineContext = MyContinuationInterceptor())
    , but the interceptor never seems to trigger. I have done something similar with an Interceptor and
    withContext(MyContinuationInterceptor()) { ... }
    . That works, but thought I would "plug it in" at the "top" to see if I could do that. Is it at all possible?
    c
    m
    29 replies · 3 participants
  • d

    Daniele B

    02/18/2021, 3:17 PM
    Running commonTest in a KMM project: when I call a function that uses Ktor Client I get this warning:
    SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
    SLF4J: Defaulting to no-operation (NOP) logger implementation
    SLF4J: See <http://www.slf4j.org/codes.html#StaticLoggerBinder> for further details.
    is it normal?
    c
    a
    12 replies · 3 participants
  • o

    olfek

    02/18/2021, 7:15 PM
    var myVariable : String? = null
    
    fun main(args: Array<String>): Unit {
        myVariable = "Hello World"
        io.ktor.server.netty.EngineMain.main(args)
    }
    
    @Suppress("unused") // Referenced in application.conf
    @kotlin.jvm.JvmOverloads
    fun Application.module(testing: Boolean = false) {
        // myVariable is null here
    }
    s
    6 replies · 2 participants
  • n

    napperley

    02/18/2021, 11:46 PM
    The Ktor Client Curl library isn't meeting expectations when it comes to stability 😞. Memory usage isn't under control, and there are other stability issues. When using the library in a Kotlin Native program targeting linuxX64 the library leaks memory, and will often fail to send all HTTP requests (no errors appear, including exceptions). Over the course of a few hours (with the program started from around 10 am yesterday) the reserved memory usage is over 72 MB and growing 😦, which is very bad compared to the Kotlin Native program using libcurl instead where the reserved memory usage is around 15 MB and the memory usage doesn't grow (is stable). A Kotliner shouldn't have to to worry if the Kotlin library they are using is leaking memory. This is a classic case of the Ktor team dropping the ball on memory management with some of the Ktor libraries they are developing/maintaining. All I want as a Kotliner using this library is stability, stability, stability!
    👀 3
    💯 3
    ✔️ 2
    1 reply · 1 participant
Powered by Linen
Title
n

napperley

02/18/2021, 11:46 PM
The Ktor Client Curl library isn't meeting expectations when it comes to stability 😞. Memory usage isn't under control, and there are other stability issues. When using the library in a Kotlin Native program targeting linuxX64 the library leaks memory, and will often fail to send all HTTP requests (no errors appear, including exceptions). Over the course of a few hours (with the program started from around 10 am yesterday) the reserved memory usage is over 72 MB and growing 😦, which is very bad compared to the Kotlin Native program using libcurl instead where the reserved memory usage is around 15 MB and the memory usage doesn't grow (is stable). A Kotliner shouldn't have to to worry if the Kotlin library they are using is leaking memory. This is a classic case of the Ktor team dropping the ball on memory management with some of the Ktor libraries they are developing/maintaining. All I want as a Kotliner using this library is stability, stability, stability!
👀 3
💯 3
✔️ 2
More focus should be placed on stability/performance, and less on new features. The newer versions of Ktor Client Curl seem to be less stable/performant than the older versions.
View count: 5