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
  • s

    Seb Jachec

    10/27/2022, 3:03 PM
    We’ve had several crash reports mention unhandled OkHttp exceptions (
    SocketTimeoutException
    ,
    ConnectTimeoutException
    ) for our KMM Android app using Ktor client 2.1.2 and the OkHttp engine factory. Is it intentional that engine exceptions aren’t caught (have I misunderstood something 😅), or is this actually a Ktor bug?
    j
    • 2
    • 2
  • c

    Christian Lippka

    10/27/2022, 5:34 PM
    I have a curious case here. I used https://start.ktor.io/ to start a new project, I leave everything default and only added two plugins • Pebble • kotlinx.serialization Now if these two blocks here
    install(ContentNegotiation) {
      json()
    }
    install(Pebble) {
        loader(ClasspathLoader().apply {
            prefix = "templates"
        })
    }
    are executed in this order, going to /pebble-index gives me an exception on the backend
    kotlinx.serialization.SerializationException: Serializer for class 'PebbleContent' is not found.
    As soon as I change the order how those two blocks are called without changing anything else it works as expected. Is there something I’m missing or not understanding or should a file an issue for this? To reproduce you just have to download a template with those two plugins and in
    Application.kt
    switch the order of
    configureSerialization()
            configureTemplating()
    to toggle the error. It looks like the order of those calls in
    Application.kt
    depends on the order you added those plugins in the web ui.
    a
    • 2
    • 1
  • m

    mserralta

    10/28/2022, 6:55 AM
    Is anyone using elastic - APM to monitor a ktor server? We are able to Use the elastic apm agent but it is not generating logs for the requests received.
  • a

    Alex Styl

    10/28/2022, 8:22 AM
    is it possible to listen to the progress it takes to receive a multipart file in a ktor server? I have a ktor server running on android and I would like to display a progress bar for files being uploaded to the server via POST. with some debugging i noticed that reading each part (of the multipart) takes the longest time
    a
    • 2
    • 6
  • l

    Leon Kiefer

    10/28/2022, 2:19 PM
    Hi, is is possible to create a
    StateFlow<HttpClient>
    which returns/caches a client based on a
    Flow<HttpClientConfig>
    so the client is update/a new client is created when the config is updated, but at the same time the old clients are cleaned up automatically, for example by the GC? In our use case we need to configure all our http clients dynamically during app runtime and the configuration is a Flow which can change at any time.
    a
    • 2
    • 8
  • t

    trashcoder

    10/28/2022, 5:01 PM
    hello, i use a ktor client and i currently try to supply a base URL using the
    DefaultRequest
    plugin as described here: https://ktor.io/docs/default-request.html#configure i tried suppling the URL as complete string:
    defaultRequest {
        url("<https://ktor.io/docs/>")
    }
    and also tried setting the URL parameters by myself:
    url {
        protocol = URLProtocol.HTTPS
        host = "<http://ktor.io|ktor.io>"
        path("docs/")
    }
    the base URL i try to set is:
    <https://api.ws.sonos.com/control/api/v1>
    during debugging, the plugin shows the correct URL including all path segments. ✅ but the
    GET
    request is executed without the path segments. ⛔ i receive this response (path is missing):
    You don't have permission to access "http&#58;&#47;&#47;api&#46;ws&#46;sonos&#46;com&#47;households" on this server.
    for request:
    httpClient.get("/households")
    am i doing something wrong? is this a known issue?
    • 1
    • 3
  • e

    Eli

    10/29/2022, 11:29 AM
    Hello! Is it possible to have a custom plugin act as a “middleware” that can abort the whole pipeline(the request) ? When calling “call.respond” , we see that it still continues to other Phases in the background. (why doesn’t call.respond() call “finish()” ?) There’s no access to the pipeline.finish() method when implementing the custom plugin Hook, so we can’t even call it manually ourselves. Our use-case: After the “validate { }” function, we need to check whether our user has “profile completed” status (by checking his claims on the JWT), and if not - respond with some status. But “validate” block itself only has 2 options (if principal is null -> it returns 401, otherwise it just proceeds, so no option to have a third option to it). And if I implement a custom plugin, even if I do there “call.respond(..)” it still proceeds to other plugins instead of finishing the whole pipeline I elaborated more on it here : https://stackoverflow.com/questions/74243213/how-to-stop-pipeline-in-ktors-plugins-middleware-that-sends-a-response-and-abo
    r
    • 2
    • 6
  • f

    Fudge

    10/30/2022, 5:24 AM
    I saw this issue was fixed, but there's no explanation how? https://youtrack.jetbrains.com/issue/KTOR-2501 Is there a way to get the raw client ip address now?
    a
    • 2
    • 2
  • a

    Austin Pederson

    10/31/2022, 7:10 PM
    Hey all, is there any way to get the path provided to the
    get() {...}
    route from a plugin? If not, is there at least a way where I can get the parameters from a request inside a plugin?
    a
    • 2
    • 4
  • p

    Partho Paul

    11/01/2022, 3:56 PM
    Hello! I’ve noticed a few spikes in response time of my microservice’s APIs. Upon further debugging, I observed that when multiple concurrent requests hit my service, then a few of them gets processed with some delay. I tried increasing the
    runningLimit
    of my Netty engine but it didn’t help. Did anybody else ever came across this issue? ktor version: 2.1.1
  • i

    IsaacMart

    11/01/2022, 4:15 PM
    I want to pass color from my backend in ktor over to android which is my client. How can i achieve it in ktor? Previously i was doing it from android using androidx graphical compose. Any guide will greatly appreciated.here is my model in ktor
    c
    • 2
    • 2
  • m

    Malachi Holden

    11/02/2022, 4:08 AM
    Hello all. I was wondering if anyone knows about this error:
    java.net.ConnectException: Failed to connect to localhost/127.0.0.1:8080
    I have a ktor server and an android app running on the same multiplatform project. Google doesn't say anything about the error except for this https://stackoverflow.com/questions/62500669/ktor-android-local-http-server-throws-error. I tried the solution and got nothing
    a
    m
    • 3
    • 5
  • d

    Dirk

    11/02/2022, 1:14 PM
    Hello, I have a problem with the Ktor client (JS). If the addressed api returns the status 302 Found for a temporary redirect and the client was configured with followRedirects = false, the status is not returned. In this case, the status is 0. Is there a special reason for this or is this a bug?
    a
    • 2
    • 3
  • r

    rocketraman

    11/02/2022, 3:35 PM
    Anyone using ktor + micrometer metrics + google cloud stackdriver? I'm finding ktor metrics are costing me upwards of $30/day on a mostly idle app. The amount of data that Google says is being received for these metrics, and what the code is apparently sending for each request seems out of whack. Anyone else seen this and figured out what is happening?
    r
    • 2
    • 4
  • a

    Austin Pederson

    11/02/2022, 6:01 PM
    Hey is there any sort of diagram out there that shows the order of execution for the various phases in which a plugin can execute? (i.e. something like CallSetup->CallReceive->.....->ResponseSent)
    a
    • 2
    • 3
  • a

    Austin Pederson

    11/02/2022, 10:24 PM
    Is there any way to get the response body from a plugin? I know I can get the OutgoingContet, but I can't figure out how to turn that into something usable for myself
    a
    • 2
    • 3
  • i

    IsaacMart

    11/03/2022, 9:52 AM
    Kindly assist on how i can query a list of taskers based on an embedded item"category_skill" inside Skill in ktor
  • m

    Mateu

    11/03/2022, 11:16 AM
    Hi, dows anyone has a sample of a ktor server with JWT with a ktor client connecting to it? The documentation on JWT server is quite ok (at least I managed to make it work). However I don't see how to connect the client using the bearer auth. Thanks,
    h
    k
    • 3
    • 8
  • k

    Kristian Nedrevold

    11/05/2022, 1:43 PM
    Does anyone have any experience using apache cassandra with ktor?
  • a

    Andrew O'Hara

    11/05/2022, 10:05 PM
    I'd like to configure one of my ktor apps for AWS Lambda deployment. I'm a big fan of http4k's serverless-lambda plugin for http apis, and am looking for something similar. I understand kotless exists, but it's far more intrusive than I'm looking for. All I need is an adapter for the AWS Lambda ApiGatewayV2 interface. Does such an adapter exist outside kotless?
  • l

    Luiz Aguiar

    11/07/2022, 2:22 PM
    Hello folks... I have a more complicated application configuration question. Imagine a carmaker application, that runs on multiple environments for each carmaker. • tesla - development, staging, production • honda - development, testing, staging, production • ford - development, qa, staging, production I think you got the idea... every "profile" can have multiple envs, each one needs its own configuration values. questions: is it possible to setup a Ktor application to fit these needs? is using
    -config
    via command line the best approach?
    java -jar sample-app.jar -config=anotherfile.conf
    a
    • 2
    • 3
  • s

    Sergey Aldoukhov

    11/07/2022, 3:00 PM
    Hi team, I have an OAuth/authentication best practices question. In my app, I have a few pages that need to be OAuth authenticated. On each of these pages, I check for the user session first and redirect to login (“/login” is the one under
    authenticate("auth-oauth-google")
    ):
    val userSession: UserSession = call.sessions.get() ?: return@get call.respondRedirect("/login")
    But as a result of successful authentication, I redirect to one of my pages:
    get("/auth/callback") {
                    val principal: OAuthAccessTokenResponse.OAuth2? = call.authentication.principal()
                    call.sessions.set(UserSession(principal?.accessToken.toString()))
                    call.respondRedirect("/status")
                }
    It worked fine when I had only one page under OAuth. But for multiple, how do I redirect to the one that invoked the OAuth flow? I’d like to avoid having a “landing” page that requires OAuth - my users most probably will use links/bookmarks to go to specific pages.
    e
    a
    • 3
    • 4
  • l

    leandro

    11/07/2022, 7:50 PM
    has anyone provided an instance of
    NSURLSession
    to ktor’s
    HttpClient
    ? something like
    engine {
          val config = NSURLSessionConfiguration.defaultSessionConfiguration()
          val session = NSURLSession.sessionWithConfiguration(config)
          usePreconfiguredSession(session)
       }
    It’s hard to debug the real issue but it basically does not work. The iOS app does not crash, but no network call is made.
    a
    r
    • 3
    • 10
  • c

    Cyril NB

    11/07/2022, 10:01 PM
    Hello, as Heroku free plan is being terminated, what is your best alternative to host a simple Ktor REST API server? Thanks a lot
    t
    s
    • 3
    • 4
  • m

    Miroslav Sobotka

    11/10/2022, 10:34 PM
    Does anyone know how to do this, please? 🙂
    a
    • 2
    • 4
  • s

    Sam Gammon

    11/10/2022, 11:37 PM
    hey ktor team
  • s

    Sam Gammon

    11/10/2022, 11:38 PM
    i am writing a higher-order framework and am thinking of adopting ktor with a module to support it
  • s

    Sam Gammon

    11/10/2022, 11:38 PM
    but i am curious, what is the preferred DI system with ktor? is it koin? is there a good one that leverages KSP and MPP and would be the future-safe choice?
  • x

    xxfast

    11/11/2022, 3:32 PM
    Is there a way to change these client configurations during runtime, after they have been configured?
    install(Logging) {
      this.logger = get()
      this.level = ALL
    }
    a
    • 2
    • 2
  • l

    Louis Gautier

    11/11/2022, 4:46 PM
    Hey I have an issue when using my KMP lib on Android / Desktop I build a simple KMP with Ktor. I’m targeting Android and Desktops for the moment I configured the ktor engine as specified here The lib is builded as expected But when I call my service in android or on desktop (mac M1) , I got the following error (or similar error with Apache)
    java.lang.NoClassDefFoundError: Failed resolution of: Lio/ktor/client/engine/okhttp/OkHttp;
    Caused by: java.lang.ClassNotFoundException: Didn't find class "io.ktor.client.engine.okhttp.OkHttp" on path: DexPathList[[dex file "/data/data/com.louis.androidappsample/code_cache/.overlay/base.apk/classes3.dex", dex file "/data/data/com.louis.androidappsample/code_cache/.overlay/base.apk/classes.dex", zip file "/data/app/~~j1M4G7GVnLQAYjWuRlSLCA==/com.louis.androidappsample-ETUEUYx9UiPhzUHXlOvm1Q==/base.apk"],nativeLibraryDirectories=[/data/app/~~j1M4G7GVnLQAYjWuRlSLCA==/com.louis.androidappsample-ETUEUYx9UiPhzUHXlOvm1Q==/lib/arm64, /system/lib64, /system_ext/lib64]]
    I’ve tried everything. Clean and invalidate, remove all kind of caches, downgrade Ktor to 1.6.8, trying different engines..I don’t know how to solve that My targets are configured like this :
    android {
        publishAllLibraryVariants()
    
    }
    
    jvm {
        compilations.all {
            kotlinOptions.jvmTarget = "11"
        }
    }
    And sourceSet :
    val commonMain by getting {
        val commonMain by getting {
            dependencies {
                implementation(Ktor.Core)
                implementation(Ktor.ContentNegotiation)
                implementation(Ktor.Json)
                implementation(Ktor.Logging)
    
                implementation(Koin.Core)
            }
        }
    }
    
    val androidMain by getting {
        dependencies {
            implementation(Ktor.OkHttp)
            implementation(Android.Material)
        }
    }
    
    val jvmMain by getting {
        dependencies {
            implementation(Ktor.Apache)
        }
    }
    Thanks !
    a
    • 2
    • 4
Powered by Linen
Title
l

Louis Gautier

11/11/2022, 4:46 PM
Hey I have an issue when using my KMP lib on Android / Desktop I build a simple KMP with Ktor. I’m targeting Android and Desktops for the moment I configured the ktor engine as specified here The lib is builded as expected But when I call my service in android or on desktop (mac M1) , I got the following error (or similar error with Apache)
java.lang.NoClassDefFoundError: Failed resolution of: Lio/ktor/client/engine/okhttp/OkHttp;
Caused by: java.lang.ClassNotFoundException: Didn't find class "io.ktor.client.engine.okhttp.OkHttp" on path: DexPathList[[dex file "/data/data/com.louis.androidappsample/code_cache/.overlay/base.apk/classes3.dex", dex file "/data/data/com.louis.androidappsample/code_cache/.overlay/base.apk/classes.dex", zip file "/data/app/~~j1M4G7GVnLQAYjWuRlSLCA==/com.louis.androidappsample-ETUEUYx9UiPhzUHXlOvm1Q==/base.apk"],nativeLibraryDirectories=[/data/app/~~j1M4G7GVnLQAYjWuRlSLCA==/com.louis.androidappsample-ETUEUYx9UiPhzUHXlOvm1Q==/lib/arm64, /system/lib64, /system_ext/lib64]]
I’ve tried everything. Clean and invalidate, remove all kind of caches, downgrade Ktor to 1.6.8, trying different engines..I don’t know how to solve that My targets are configured like this :
android {
    publishAllLibraryVariants()

}

jvm {
    compilations.all {
        kotlinOptions.jvmTarget = "11"
    }
}
And sourceSet :
val commonMain by getting {
    val commonMain by getting {
        dependencies {
            implementation(Ktor.Core)
            implementation(Ktor.ContentNegotiation)
            implementation(Ktor.Json)
            implementation(Ktor.Logging)

            implementation(Koin.Core)
        }
    }
}

val androidMain by getting {
    dependencies {
        implementation(Ktor.OkHttp)
        implementation(Android.Material)
    }
}

val jvmMain by getting {
    dependencies {
        implementation(Ktor.Apache)
    }
}
Thanks !
a

Aleksei Tirman [JB]

11/14/2022, 8:37 AM
Maybe enabling multidex will help.
l

Louis Gautier

11/14/2022, 9:17 AM
I’ll try, but my lib is empty (2 classes for the moment). It’s seems weird
a

Aleksei Tirman [JB]

11/14/2022, 10:03 AM
I think all your dependencies and their dependencies counts.
l

Louis Gautier

11/14/2022, 11:50 AM
According to that part multidex is enabled by default on API 21 or greater (i’m currently API 24)
View count: 17