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

    Levente

    03/25/2021, 11:57 AM
    Hi all! Thanks for having me! I want to implement session-based authorization, but was unable to find documentation on this in the ktor docs. I'd like to ask some more questions about this. Can I do so here?
    h
    1 reply · 2 participants
  • f

    Fábio Carneiro

    03/25/2021, 2:56 PM
    in ktor websockets, am I expected to manage which client I am talking to or the
    DefaultWebSockerServerSession
    is already a 1:1 connection between the server and client?
    j
    20 replies · 2 participants
  • j

    Jordan Foo

    03/25/2021, 7:04 PM
    Hi all, is it bad to have more than one ktor server in a jvm? We're trying to do different ports for different APIs for security reasons, but I can't find docs on if this is a bad idea or not
    o
    d
    3 replies · 3 participants
  • d

    Didier Villevalois

    03/26/2021, 4:47 PM
    Hi everyone! I have a question that may or may not be out of scope of this channel. Sorry in advance. I successfully setup OAuth2 with ktor and keycloak. I can see that the authentication works correctly from the log of keycloak and the logging of the
    HttpClient
    used by my
    OAuthAuthenticationProvider
    . It correctly receives the
    access_token
    . Now my question is what to do from there. I did put all my routes (this app is fully private) in
    authenticate
    , that is: my index
    /
    route, my static
    /static
    route (which serves the
    output.js
    file of my app) and my
    /data
    web-socket route. However, it seems that every requests are handled by
    authentication
    , the requests to
    /static/output.js
    and to
    /static/favicon.ico
    are all been redirected to keycloak and silently back to ktor. (The requests to my
    /data
    websocket also hangs but...) It seems to me that I should put the
    access_token
    in my response as cookie or something in order for ktor to know it doesn't have to ask for a redirect. But it is not clear from the documentation what I should exactly do for
    authentication
    to reuse the previously obtained
    access_token
    . Thanks in advance for your help.
    r
    2 replies · 2 participants
  • a

    Arnau Miro

    03/27/2021, 10:33 PM
    Hi guys! Which is the best way to intercept request and response to print body on logs? I have something like this but event with DoubleReceive I get io.ktor.request.RequestAlreadyConsumedException
    environment.monitor.subscribe(Routing.RoutingCallStarted) { call: RoutingApplicationCall ->
        println("Route started: ${call.route}")
        runBlocking { println(call.receiveText()) }
    }
    r
    h
    7 replies · 3 participants
  • s

    spierce7

    03/28/2021, 3:51 PM
    Has anyone gotten graalvm native-image working with just ktor on any of the server engines (i.e. netty)? Someone gave me an example of it working with micronaut + ktor, but I haven’t been able to get it working with just ktor, as graal has lots of problems with netty it seems.
    s
    8 replies · 2 participants
  • a

    adk

    03/28/2021, 5:45 PM
    It is possible to get ktor to run on a dynamically-allocated port, and then tell you what port it is running on?
    c
    3 replies · 2 participants
  • n

    Nikita Khlebushkin

    03/30/2021, 12:33 PM
    Hello! I'm getting weird issue here
    Rejecting re-init on previously-failed class java.lang.Class<okhttp3.internal.platform.ConscryptPlatform$platformTrustManager$2>: java.lang.NoClassDefFoundError: Failed resolution of: Lorg/conscrypt/ConscryptHostnameVerifier;
    Ktor 1.5.2, Android app with multiplatform networking library
    :youtrack: 1
    y
    4 replies · 2 participants
  • s

    Susheel

    03/30/2021, 7:09 PM
    https://github.com/ktorio/ktor/blob/master/ktor-client/ktor-client-core/common/src/io/ktor/client/statement/HttpResponse.kt#L81 For a case when Job is null, I'm seeing an NPE. I'm wondering how I would go about fixing it. I could add a job to the dispatcher I'm assigning the code to? Or I could just do a null-check? But is this a known issue? Will there be a fix for it?
    r
    1 reply · 2 participants
  • r

    rnett

    03/31/2021, 3:51 AM
    Routing question: I'm trying to support multiple "functions", each which has some custom resolution code, so I'm putting it in a
    route("{...}")
    . However some of the functions make use of Ktor routing like
    authenticate
    . This doesn't play nice with the routes because of ambiguity. If I put the authenticate and the handlers (w/
    handle
    ) in the same route, the authenticate is always taken. If I each handler in it's own
    route("{...}")
    , the sibling
    authenticate
    is never taken. And even without that, if I have two of the same authenticates at the same level (one is optional, one isn't), the first is always taken. Is there a way to do something like this, i.e. have routes with fallthrough the request isn't handled? I'm currently using a
    RouteSelector
    to do this, but it's quite a bit of overhead for something relative (at least conceptually) simple.
    2 replies · 1 participant
  • c

    Cyrille QUÉMIN

    03/31/2021, 8:17 AM
    Hey all, I have a question: what is the difference between:
    install(HttpTimeout) {
        requestTimeoutMillis =
        connectTimeoutMillis =          
    }
    And
    engine {
        endpoint {
            connectTimeout = 
            connectRetryAttempts = 
        }
        requestTimeout = 
    }
    In particular I could see the timeout from
    HttpTimeout
    working but I could also see the default value of
    engine.requestTimeout
    being used (before I changed it). Also, which
    connectTimeout
    will be used ?
    HttpTimeout
    of the one
    engine.endpoint
    ? Note, I am using the CIO engine with Ktor 1.4.2
    r
    2 replies · 2 participants
  • d

    Denis Ismailaj

    04/02/2021, 10:31 AM
    Hello! I saw that issue #571 (Adding Kotlin/Native support for Ktor Server) was left open on the milestone for 1.4.0. Is this still in the works?
    b
    1 reply · 2 participants
  • j

    Jakob K

    04/02/2021, 1:02 PM
    Is it possible to make HTTP requests to the Docker Engine API with Ktor? I am asking because that API is using a Unix socket.
    n
    4 replies · 2 participants
  • m

    Michal Klimczak

    04/04/2021, 6:15 PM
    I'm losing a few bytes while using
    ByteReadChannel
    and I have no idea why.
    someCall()
                .execute { response: HttpResponse ->
                    var offset = 0
                    val channel = response.receive<ByteReadChannel>()
                    val contentLen = response.contentLength()?.toInt() ?: 0
                    val temp = ByteArray(1024)
                    while (!channel.isClosedForRead) {
                        val read = channel.readAvailable(temp)
                        if (read <= 0) break
                        offset += read
                        println("$offset / $contentLen")
                    }
                    println("End: $offset / $contentLen")
    ...
    94331817 / 94336479
    94332841 / 94336479
    94333857 / 94336479
    End: 94333857 / 94336479
    The worst part is that every time the result is a tiny bit different. End: 94334201 / 94336479 End: 94334515 / 94336479 That's a simplified piece of code, normally I write to ios storage - it's a zip file and the checksum is wrong (although it seems to unzip fine, maybe one of many files is corrupt, dunno). When I download this file via browser, the checksum is fine. ktor 1.5.3. Any ideas what I might be doing wrong?
    3 replies · 1 participant
  • h

    hhariri

    04/05/2021, 12:32 PM
    Ktor 1.5.3 available https://twitter.com/JetBrainsKtor/status/1379049254698819584
    🎉 7
    👍 8
    👍🏼 2
    t
    e
    3 replies · 3 participants
  • h

    hhariri

    04/05/2021, 8:56 PM
    Here’s a teaser for you…
    :kotlin-intensifies: 27
    t
    3 replies · 2 participants
  • ł

    Łukasz Bednarczyk

    04/06/2021, 7:38 AM
    @el5 what about request validation? Have you planned it in next version? - I cannot find Ktor roadmap 😞
    👍🏼 1
    👍 2
    e
    h
    7 replies · 3 participants
  • k

    klausner

    04/06/2021, 5:46 PM
    There is an error in 1.5.2 version changelog. This follow issue was not included to released version
    Add an option to disable URL Encoding
    <https://youtrack.jetbrains.com/issue/KTOR-553>
    This issue was imported from GitHub issue: <https://github.com/ktorio/ktor/issues/1351>
    
    Subsystem ktor-client, ktor-http/common
    
    Is your feature request related to a problem? Please describe. ktor-client cannot be used for URLs which are not supported by the URL Encoding format.
    
    I failed to replace an HTTP client with ktor-client just because we needed to call a URL like /api?k1=v1;k1=v2 (non-encoded ; instead of %3B). As far as I checked, there's no way to bypass URL Encoding in ktor-client.
    
    In other libraries, typically we can set parameters just like a simple Map<String, List<String>>. I agree that it's better to always use a sanitized request object, but it would be too strict not to have an option to disable encoding.
    
    Describe the solution you'd like I opened a PR to add an option to bypass the URL Encoding when building a URL.
    
    Motivation to include to ktor I believe that users of ktor-client shouldn't be blocked by the implementation of a server URL because they might not have control over it.
    
    (Please let me know if there's an option to resolve the above problem.)
    r
    1 reply · 2 participants
  • t

    tim

    04/07/2021, 3:22 PM
    I'm using ktor's http client (tried jetty and cio) for some tests against an api which expects a jwt in the request. when the request doesn't have a jwt the server returns 401/Unauthorized. I'm confused about the decision decision as to why the client throws if the server responds with 401/unauthorised. Am i wrong in thinking that seems to be an extreme response to a valid http response?
    r
    2 replies · 2 participants
  • c

    christophsturm

    04/07/2021, 6:08 PM
    /**
         * Register a route resolution trace function.
         * See <https://ktor.io/servers/features/routing.html#tracing> for details
         */
        public fun trace(block: (RoutingResolveTrace) -> Unit) {
            tracers.add(block)
        }
    ^ thats from the trace function in routing. sadly the link is a 404
    1 reply · 1 participant
  • c

    christophsturm

    04/08/2021, 8:25 AM
    so i added route tracing, because after a ktor update one of my routes 404s. the output looks like this:
    Trace for [api, weight]
    /, segment:0 -> SUCCESS; Parameters [static-content-path-parameter=[api, weight]] @ ///{...}/(method:GET))
      //, segment:0 -> SUCCESS; Parameters [static-content-path-parameter=[api, weight]] @ ///{...}/(method:GET))
        ///(method:GET), segment:0 -> FAILURE "Not all segments matched" @ ///(method:GET))
        ///{...}, segment:2 -> SUCCESS @ ///{...}/(method:GET))
          ///{...}/(method:GET), segment:2 -> SUCCESS @ ///{...}/(method:GET))
      /api, segment:0 -> FAILURE "Lost in ambiguity tie" @ /api)
    1 reply · 1 participant
  • m

    MBegemot

    04/08/2021, 8:43 AM
    I'm trying to build a filter for incoming calls produced parallelly let's say that you call simultaneously from the client a route called test, like test(0),test(0),test(0),test(1),test(3) test(1). The purpose is that in the server simultaneous calls to the same key are delayed till the result of first one is produced. That's the current solution I'm working on https://gist.github.com/Abegemot/157a548ac4c1725c66fc45e584a66cdd . Unfortunately it does not solve the problem totally ..... If someone could have a look at it I'll really appreciate. I really thing it is a very useful feature to have.
    1 reply · 1 participant
  • m

    Marc Knaup

    04/08/2021, 3:22 PM
    Is there a way to print all Ktor routes for debugging?
    j
    7 replies · 2 participants
  • s

    Shan

    04/08/2021, 8:34 PM
    Hey all. I'm getting a
    JsonDecodingException
    (from kotlinx.serialization) which I believe is being caused by the source string being cut off after decoding it to a String from a
    ByteArray
    with the util extension function on
    ByteReadChannel
    .
    Unexpected JSON token at offset 195068: EOF JSON input: .....text !","field":0.0,"te
    This particular error can only be thrown if the current position when iterating over the source string is >= the last index of the string, and my JSON is not being fully parsed, so I am assuming that the String is being truncated somehow before parsing.
    ...
    .onSuccess { it: HttpResponse ->
        val receiveString = it.content.toByteArray().decodeToString()
        ...
        //later
        return json.decodeFromString(receiveString) //cast to my return type T
    }
    Does anyone have any insight as to why this might be happening? Am I receiving my
    HttpResponse
    content
    incorrectly? Note: I'm not using the kotlinx
    JsonFeature
    , using it separately. My only idea right now is that it is failing to allocate the entire string due to OOM and this is just the first place exposing it, but I'm pretty sure this would fail with a different exception if that was the case.
    decodeToString()
    is experimental but it was working as intended until very recently. I upgraded to Ktor 1.5.3 recently, but can't confirm that the version upgrade is what triggered it as I can't repro it locally, just see it in a crash report. It happens very infrequently, like ~.001% of all requests.
    r
    1 reply · 2 participants
  • o

    okarm

    04/09/2021, 12:40 PM
    HttpClient
    is to be treated as a lightweight ephemeral object. Instantiating `HttpClient`s should be done liberally.
    HttpClient
    itself is not resource heavy, all instances manage the underlying installed heavyweight engine in a manner consistent with the proper usage of that engine. Example:
    OkHttp
    engine forks a statically allocated base
    OkHttpClient
    by way of
    newBuilder()
    . Same goes for other engines. Is the above paragraph true? Assuming the clients are properly closed and all...
    👀 1
    m
    r
    4 replies · 3 participants
  • d

    Dominick

    04/10/2021, 12:40 AM
    How should I go about creating a media upload system? I know you could just add a form body and accept a file, then download it. Is that the best way? Is there a way to use a LetsEncrypt SSL certificate instead of a JKS with KTOR?
    h
    1 reply · 2 participants
  • o

    okarm

    04/10/2021, 6:27 PM
    Does Ktor always throw a subclass of
    RuntimeException
    ? Edit: nope, just found the
    BadContentTypeException : Exception
    .
    try { client.request() } catch(e: Exception)
    it is then.
    c
    4 replies · 2 participants
  • h

    Harry B

    04/11/2021, 3:00 PM
    Hey! How do you send data to a websocket outside of the client.wss block e.g
    class example {
        private val ktorClient = HttpClient(Js) {
            install(WebSockets)
        }
        override suspend fun open() {
            ktorClient.wss(
                method = HttpMethod.Get,
                host = "localhost",
                port = 80, path = "/example"
            ) {
                
                val frame = incoming.receive()
                when (frame) {
                    is Frame.Text -> println(frame.readText())
                    is Frame.Binary -> println(frame.readBytes())
                }
            }
        }
    
        override fun close() {
            TODO("Not yet implemented")
        }
    
        override fun <T> sendData(data: T) {
            // Send to WS here
        }
    }
    r
    5 replies · 2 participants
  • m

    MBegemot

    04/11/2021, 5:00 PM
    I'm getting java.net.ProtocolException unexpected end of stream , at random times at client side. I think I haven't seen this error, only since last 1.5.3 update ... thanks
    1 reply · 1 participant
  • d

    dave08

    04/12/2021, 3:41 PM
    Hi! Does `withTestApplication`'s
    handleRequest
    have a way to handle requests to different ports (in the routing I have
    port(...) { ... }
    )? (This is an older api that's running on Ktor version 1.3.0)
    1 reply · 1 participant
Powered by Linen
Title
d

dave08

04/12/2021, 3:41 PM
Hi! Does `withTestApplication`'s
handleRequest
have a way to handle requests to different ports (in the routing I have
port(...) { ... }
)? (This is an older api that's running on Ktor version 1.3.0)
I figured it out:
addHeader(HttpHeaders.Host, ":8050")
View count: 3