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

    Andrey Tabakov

    09/20/2022, 6:49 AM
    Hi I have a problem with ktor websockets, it closes the channel from time to time (randomly, I have no idea why). Client channel getting error 1006 (closed abnormally), how can I figure out what's going on? Is there a mechanism for auto-reconnect?
    a
    • 2
    • 3
  • c

    cpe

    09/20/2022, 10:13 AM
    Hi, I’m implementing a service providing endpoints with and without authentication. After repeating the same procedures for some endpoints I wonder if there is a better way in KTor providing repeating context information for services, let me try to give an abstract example:
    routing {
      get("/test") {
        call.respondText("test called")
      }
      authenticate("auth-jwt") {
        route("/featureA") {
          get("/") {
            val principalSubject = call.principal<JWTPrincipal>()?.subject
            featureAService.handleGet(call, principalSubject)
          }
          post("/") {
            val principalSubject = call.principal<JWTPrincipal>()?.subject
            featureAService.handlePost(call, principalSubject)
          }
          put("/") {
            val principalSubject = call.principal<JWTPrincipal>()?.subject
            featureAService.handlePut(call, principalSubject)
          }
        }
        route("/featureB") {
          get("/") {
            val principalSubject = call.principal<JWTPrincipal>()?.subject
            featureBService.handleGet(call, principalSubject)
          } 
        }
      }  
    }
    In this case I’d like to provide the principalSubject to each method (in reality there are a few more context parameters that are shared across those methods like parameters etc.). I don’t want to start each method with retrieving unsers and other context parameters and I also don’t want to repeat those lines in the
    routing
    section. Is there any way to reduce the amount of code here by having some preprocessor (could then use
    context-receivers
    )?
    a
    r
    s
    • 4
    • 17
  • m

    Milton Johansson

    09/20/2022, 10:54 AM
    Hey will share this here also, probably fits better here! I use ktor version 2.0.3 and kotlin version 1.7.10
    • 1
    • 1
  • a

    ayodele

    09/20/2022, 7:18 PM
    Hi, I've tried to debug this situation but I've been unable to:
    val dnb = "<https://www.dnb.com/apps/dnb/servlets/CompanySearchServlet>"
    val res = client.get(dnb) {
        url {
            parameters.append("pageNumber", "1")
            parameters.append("pageSize", "5")
            parameters.append("searchTerm", "NQB8 Limited")
            parameters.append(
                "token",
                "eyJwNCI6IklvTEh3WVN6SkZTaDJLUG0zYU41c1NacnZLUFBNUE1MTlBSTE1RIiwicDIiOjksInAzIjozOCwicDEiOjE2NjM2MzI0NjgyMzd9"
            )
        }
    }
    println(res)
    It works on postman, but it kinda freezes on Ktor with no response.
    a
    • 2
    • 3
  • l

    Luiz Aguiar

    09/20/2022, 8:20 PM
    Any suggestion of a scheduling library that works nicely with Ktor?
    a
    • 2
    • 2
  • i

    Ioannis Mavroukakis

    09/21/2022, 2:11 PM
    Hello lovely folks! I have a question with regards to
    HttpClient
    re-use. What is the accepted wisdom here? Create a new one as needed, or never
    close()
    the existing one? What do people do? Thanks!
    s
    l
    j
    • 4
    • 12
  • d

    Dariusz Kuc

    09/22/2022, 12:47 AM
    Hello 👋 While using Ktor HttpClient Is there a way to automatically set
    Content-Length
    header (default in v1.6) vs
    Transfer-Encoding: chunked
    (default in v2.0)?
    r
    • 2
    • 7
  • j

    Johnny

    09/22/2022, 9:09 AM
    Hey 👋 Is there any reason why the constructor of the
    HttpCacheEntry
    is internal? This makes it impossible to extend the
    HttpCacheStorage
    to be able to implement a custom caching solution, in which the entries could be persisted in a database (Android/iOS)
    r
    • 2
    • 1
  • k

    Keith Miller

    09/22/2022, 3:42 PM
    hello, are there any examples of handling a client file upload using the JavaScript engine? Thanks
  • k

    Kristian Nedrevold

    09/23/2022, 5:57 PM
    Is this an ok way to run backround tasks in ktor?
    suspend fun Application.runJobs(jobService: JobService) {
        withContext(this.coroutineContext) {
            launch {
                while (true) {
                    delay(1000)
                    println("hello")
                }
            }
        }
    }
    s
    a
    • 3
    • 7
  • b

    benkuly

    09/24/2022, 1:00 PM
    Is it possible to use ktor as HTTP proxy (forward/outbound proxy)? I already implemented the reverse proxy part for inbound connections, but I need it also for outbound connections. The proxy just filters request depending on some headers.
    • 1
    • 1
  • a

    Alejandro Serrano Mena

    09/25/2022, 6:33 AM
    Just because it happens to me all the time: is the ContentNegotiarion there imported from the client module (I always mix it with the server one)?
    c
    • 2
    • 5
  • m

    marzelwidmer

    09/25/2022, 8:45 AM
    Hello have somebody already done HATEOAS api with ktor?
  • j

    jeggy

    09/25/2022, 4:15 PM
    Is there any way for me to debug why my endpoint only works once? The second time I'm calling it ktor just hangs. The debugger never hits the first line within the route endpoint body. Restarting the server makes it work for 1 time again.
  • h

    hhariri

    09/26/2022, 2:07 PM
    Reminder: Folks, we’d really appreciate it if you could take 5-10 minutes to fill this survey in. It really does help us. Thanks. https://surveys.jetbrains.com/s3/ktor-annual-customer-survey-2022
    n
    • 2
    • 2
  • s

    Slackbot

    09/26/2022, 2:48 PM
    This message was deleted.
  • g

    Giuliopime

    09/26/2022, 10:17 PM
    I have a data class which looks like this:
    /**
     * Represents a single list, which can contain categories to organize list items in it
     */
    @Serializable
    data class ListDto(
        @Contextual @SerialName("_id") val id: String = ObjectId().toHexString(),
        val user_id: String,
        var name: String,
        val categories: MutableList<CategoryDto>,
        // TODO: types do be defined
        var icon: String,
        var color: String
    )
    I want the user to create a new List from the frontend so I will need to receive the list data in my ktor put route
    route("/lists") {
                get {
                    // Returns all lists
                }
    
                put {
                   // Need to receive the list data here but obviously it doesn't have an id yet
                }
    The issue is that when the user wants to create a list it will not send the list id too, 'cause that will be generated on the server after receiving the list properties like name, categories, etc... Isn't there a way to reuse the ListDto data class but fill the id variable dynamically?
    a
    • 2
    • 14
  • m

    Mihai Voicescu

    09/27/2022, 8:02 AM
    I am using rSocket with the ktor WebSockets support. Each time a client disconnects I get an Error log message. Any ideas on how I can handle it so it does not flood our server logs?
    Caused by: kotlinx.coroutines.channels.ClosedReceiveChannelException: Channel was closed
    	at kotlinx.coroutines.channels.Closed.getReceiveException(AbstractChannel.kt:1108)
    	at kotlinx.coroutines.channels.AbstractChannel$ReceiveElement.resumeReceiveClosed(AbstractChannel.kt:913)
    	at kotlinx.coroutines.channels.AbstractSendChannel.helpClose(AbstractChannel.kt:342)
    	at kotlinx.coroutines.channels.AbstractSendChannel.close(AbstractChannel.kt:271)
    	at kotlinx.coroutines.channels.SendChannel$DefaultImpls.close$default(Channel.kt:93)
    	at io.ktor.websocket.DefaultWebSocketSessionImpl$runIncomingProcessor$1.invokeSuspend(DefaultWebSocketSession.kt:204)
    	at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    	at kotlinx.coroutines.DispatchedTaskKt.resume(DispatchedTask.kt:234)
    	at kotlinx.coroutines.DispatchedTaskKt.resumeUnconfined(DispatchedTask.kt:190)
    	at kotlinx.coroutines.DispatchedTaskKt.dispatch(DispatchedTask.kt:161)
    	at kotlinx.coroutines.CancellableContinuationImpl.dispatchResume(CancellableContinuationImpl.kt:397)
    	at kotlinx.coroutines.CancellableContinuationImpl.completeResume(CancellableContinuationImpl.kt:513)
    	at kotlinx.coroutines.channels.AbstractChannel$ReceiveHasNext.completeResumeReceive(AbstractChannel.kt:947)
    	at kotlinx.coroutines.channels.AbstractSendChannel.offerInternal(AbstractChannel.kt:56)
    	at kotlinx.coroutines.channels.AbstractSendChannel.send(AbstractChannel.kt:134)
    	at io.ktor.websocket.RawWebSocketJvm$1.invokeSuspend(RawWebSocketJvm.kt:68)
    	at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    	at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
    	at kotlinx.coroutines.internal.LimitedDispatcher.run(LimitedDispatcher.kt:42)
    	at kotlinx.coroutines.scheduling.TaskImpl.run(Tasks.kt:95)
    	at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:570)
    	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
    	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:677)
    	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:664)
    a
    • 2
    • 2
  • a

    Andrey Tabakov

    09/28/2022, 11:01 AM
    Hello, I have a problem with deflater, I use ktor CIO http client on server and ktor JS http client on client, I also use a websockets, how can I gzip messages?
    b
    r
    c
    • 4
    • 79
  • n

    Niko

    09/29/2022, 5:18 PM
    I'm thinking there is a regression in Ktor 2.0 where using
    kotlinx.html
    DSL exceptions are swallowed and the result of a request is just
    *0.0.0.0* didn't send any data. ERR_EMPTY_RESPONSE
    I found this issue for Ktor 1.x: https://youtrack.jetbrains.com/issue/KTOR-756 with status of being fixed in 1.5.4. However, I'm now using Ktor JVM 2.1.1 and
    kotlinx-html-jvm:0.8.0
    , and all exceptions inside the DSL get swallowed and the log just shows
    2022-09-29 20:12:45.948 [eventLoopGroupProxy-4-3]  INFO 
                    Application - 200 OK: GET - /<path>
    Debugging the exceptions, raised exception get to the
    catch
    block in
    T.visitTag
    in
    commonMain/visit.kt
    in
    kotlinx-html-jvm
    a
    • 2
    • 7
  • p

    PHondogo

    09/29/2022, 8:48 PM
    Hello! In Ktor udp client socket there is method 'connect' wich has a remote address as one of parameters. Also in Datagram constructor there is remote address parameter as well. Why?
    a
    • 2
    • 1
  • m

    Meherdatta Chepuri

    09/29/2022, 9:20 PM
    Hello, Is it recommended to use openapi-generator to auto generate api models and functions for ktor in a KMM project?
  • y

    Yuutokata

    09/30/2022, 6:44 PM
    How can i use a proxy that authanticates with a username and password with ktor client ?
    a
    • 2
    • 1
  • y

    Yuutokata

    09/30/2022, 6:44 PM
    Enginge OkHttp
  • y

    Yuutokata

    09/30/2022, 6:45 PM
    because im getting "Exception in thread "main" java.io.IOException: Failed to authenticate with proxy"
  • c

    CLOVIS

    10/02/2022, 1:20 PM
    Is there any known issue of missing body with
    testApplication
    ? Or a proper way to debug the request response?
    a
    • 2
    • 2
  • r

    Rodrigo Silva

    10/02/2022, 6:34 PM
    Hi all. I have a form that I receive 3 fields string int file (pdf). But I'm not sure how to do this with ktor/kotlin. My class
    data class SomeClass (
    name: String,
    age: int,
    document: ByteArray (is it correct?)
    )
    fun Route.test() {
     route("/test") {
       post("/doc") {
          val receive = call.receive<SomeClass>()
    ...
    a
    a
    e
    • 4
    • 6
  • j

    João Gabriel Zó

    10/03/2022, 2:44 PM
    is there away to make Ktor Server accept connections via mTLS?
    a
    • 2
    • 1
  • j

    jamireh

    10/03/2022, 6:09 PM
    👋 I'm trying to make a companion client plugin to the provided Auth plugin; one that, at will of the developer, can rewrite the response of the next request to return an HTTP 401 to trigger the provided Auth plugin logic and ultimately, help test that the integration works correctly. Is there an example I can look at for rewriting the response through a plugin but still have other plugins process the result? I've tried intercepting using the
    sendPipeline
    after
    State
    as well as intercepting
    HttpSend
    . Both had issues that didn't meet my expectations. What I expect to happen is: 1. Developer triggers my companion plugin through a debug tool of their choice so the next API call will return an HTTP 401 2. Developer triggers another API call and within one execution context: a. My companion plugin is triggered, rewriting the response to HTTP 401 b. The provided Auth plugin is triggered, with the refresh token logic being invoked & in Bearer token providers, the
    access_token
    &
    refresh_token
    are rotated c. The provided Auth plugin retries the original API with the new
    access_token
    and returns the response
    • 1
    • 3
  • s

    Slackbot

    10/04/2022, 1:48 AM
    This message was deleted.
    l
    a
    • 3
    • 4
Powered by Linen
Title
s

Slackbot

10/04/2022, 1:48 AM
This message was deleted.
l

Lucas León

10/04/2022, 1:49 AM
@Aleksei Tirman [JB] I hope that you can help me with this issue
a

Aleksei Tirman [JB]

10/04/2022, 7:44 AM
Could you please share a code snippet for the client and information about the service endpoint if it’s public?
l

Lucas León

10/04/2022, 4:10 PM
Unfortunately, the service is not public. But here’s a snippet and what the service returns:
HttpClient {
        install(ContentNegotiation) {
            jackson ()
        }
        expectSuccess = true
        defaultRequest {
            url(URL)
            contentType(ContentType.Application.Json)
        }
    }

suspend fun postRequest(requestBody: RequestBody): String =
    <http://httpClient.post|httpClient.post> {
        setBody(requestBody)
        header("Authorization", "Basic <token>")
    }.body()
The service returns something like this:
{
  "value": "bb65bl98h4j65c95b8e65b8edb7y6ty8"
}
Nvm, fixed it using the ContentEncoding plugin. Thanks!
View count: 2