https://kotlinlang.org logo
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

    Aaron Rice

    03/14/2022, 9:33 PM
    I'm having trouble importing
    ContentNegotiation
    . In my
    dependencies
    , I have:
    implementation("io.ktor:ktor-server-content-negotiation:$ktor_version")
    implementation("io.ktor:ktor-serialization-kotlinx-json:$ktor_version")
    where
    ktor_version=2.0.0-beta-1
    . Is there something else I'm missing?
    a
    • 2
    • 2
  • k

    Karen Frangulyan

    03/15/2022, 11:25 AM
    Hey guys, I'm new to ktor and having problems with Auth plugin on mobile. Our backend returns 401 (Unauthorized) without the
    WWW-Authenticate
    header set, as a result the
    refreshToken
    is not being triggered. I tried to solve this by intercepting the responses and adding that header manually on mobile client, however, token refresh is still not triggered and I don't see that header in http response logs, even though the interceptor code is being executed. Below is the simplified version of my client setup:
    install(Logging)
        install("Fix Unauthorized headers") {
            receivePipeline.intercept(HttpReceivePipeline.Before) { response ->
                println("----------- INTERCEPTING!") // this is printed
                proceedWith(UnauthorizedResponseWrapper(response))
            }
        }
        install(Auth) {
            bearer {
                loadTokens {
                    println("---------- LOADING TOKENS!") // this is printed
                    ...
                }
                refreshTokens {
                    println("---------- REFRESHING TOKENS!") // this is NOT printed
                    ...
                }
            }
        }
    and the
    UnauthorizedResponseWrapper
    is pretty simple - just adds the header if needed:
    private class UnauthorizedResponseWrapper(response: HttpResponse): HttpResponse() {
        override val call: HttpClientCall = response.call
        override val content: ByteReadChannel = response.content
        override val coroutineContext: CoroutineContext = response.coroutineContext
        override val headers: Headers = buildHeaders {
            appendAll(response.headers)
            if (response.status == HttpStatusCode.Unauthorized && !response.headers.contains(HttpHeaders.WWWAuthenticate)) {
                println("--------- APPENDING WWWAuth header!") // this is printed!
                append(HttpHeaders.WWWAuthenticate, AuthScheme.Bearer)
            }
        }
        override val requestTime: GMTDate = response.requestTime
        override val responseTime: GMTDate = response.responseTime
        override val status: HttpStatusCode = response.status
        override val version: HttpProtocolVersion = response.version
    }
    As I said - I'm completely new to ktor, am I missing something here or maybe the header should be different to pass through Auth checks?
    a
    • 2
    • 1
  • r

    Rustam Siniukov

    03/16/2022, 2:55 PM
    hi, what version do you use?
    h
    • 2
    • 7
  • p

    PHondogo

    03/17/2022, 8:16 PM
    Hello! Could someone suggest some benchmark results for server ktor-netty performance and max active connections it can handle?
    c
    • 2
    • 1
  • c

    Constantin Cezar Begu

    03/20/2022, 5:25 AM
    Hello everyone 🙂 I am building a application using ktor (server) and exposed. I was able to build the dao for the database. I was wondering how people approached caching the data so that the transactions are faster. Create a hashmap with the id of the item for each dao? Use a h2 database on top of mysql? If anyone has dealt with it feel free to make recommendations. Thank you in advance!
    j
    • 2
    • 1
  • s

    simon.vergauwen

    03/21/2022, 3:13 PM
    Is this expecting behavior in Ktor (1.6.8)? I expected something similar to happen in both implementations, I definitely didn't expect it to crash the Ktor Server since Ktor Application's
    CoroutineScope
    is a
    SupervisorJob
    . And a
    async
    without an
    await
    is now crashing the server due to a child
    CoroutineScope
    of the Application
    SupervisorJob
    🤔 Adding
    await
    in
    notFine
    also doesn't change the behavior. It's hard to find more documentation around this, I looked around the codebase but had a hard time locating where
    execute
    is being called. Probably somewhere in the integration code with Netty, or other runtimes.
    Untitled.kt
    e
    • 2
    • 6
  • a

    Alexander Weickmann

    03/22/2022, 8:35 AM
    Hello! Ktor config can be accessed via environment.config. But this can only be done from a place where we have the environment in scope. So for example in a route, we can do call.application.environment. But how best to access config deep down in the business layer? Do we have to pass the config via parameters or is there another way? We tried by reading the .conf file ourselves with ConfigFactory.load. But this has the disadvantage that the config cannot be changed dynamically in integration tests as described here: https://ktor.io/docs/testing.html#map
    i
    a
    • 3
    • 5
  • r

    rudolf.hladik

    03/22/2022, 2:19 PM
    Is there a way to remove
    implementation("ch.qos.logback:logback-classic:$logback_version")
    from Ktor 2.0 embededServer ? it uses reflection and thats bad for
    GraalVM native-image
    a
    • 2
    • 11
  • a

    Andrew Reed

    03/22/2022, 4:45 PM
    Is there an updated release date for ktor 2.0.0? i see previously it was Feb.
    👀 1
    a
    e
    • 3
    • 5
  • l

    Lucas León

    03/22/2022, 4:56 PM
    Hi everyone! Where can I find a working retry plugin for 1.6.8?
    a
    • 2
    • 1
  • m

    Mark Schisler

    03/22/2022, 5:45 PM
    Is there a good work around for this incompatibility with
    <domain-config>
    network config on Android? The work around appears to be to drop down to fully enabling all clear text comms (which seems wild). To fix this bug, all that appears to be missing is an update to this function call to add in the hostname of the request. Is there a time table for release? This issue has existed since 1.5 and still isn’t fixed in the mainline branch. See the attached JIRA issue. https://github.com/ktorio/ktor/blob/1d56e5505135022f72ff666e08f5d83a03413b04/ktor-[…]r-network-tls/jvm/src/io/ktor/network/tls/TLSClientHandshake.kt https://youtrack.jetbrains.com/issue/KTOR-2243
    👍 1
    • 1
    • 2
  • j

    jmfayard

    03/23/2022, 11:38 AM
    What do you use for internationalization ? Any alternative to https://github.com/aymanizz/ktor-i18n
    👀 1
    s
    • 2
    • 1
  • b

    ByteZ

    03/23/2022, 3:31 PM
    I'm currently unable to properly import the ktor client dependency for some reason. I added
    ktor-client-core
    and
    ktor-client-cio
    to my pom.xml dependencies but can't access any classes even though I can see them under external libraries. I already tried invalidating my intellij caches and deleting both dependencies from my local repo. Is there something I missed or is this an intellij bug?
    a
    • 2
    • 2
  • v

    Vivek Modi

    03/23/2022, 5:41 PM
    Hey everyone, I have pre existing Android application using
    OKHTTP
    client with some`interceptors` and
    authenticator
    and iOS application using
    alamofire
    with
    interceptors
    .Both projects are huge in size. Now I want to use KMM for new api client. So How can I use these 2 http client through Ktor. I don't want to write from scratch in KMM module. Any suggestion?
    s
    d
    a
    • 4
    • 16
  • j

    Joey

    03/25/2022, 2:12 PM
    On a KMM project I'm uploading a large video from an Android device, but for some reason I get OutOfMemory exceptions even though, as far as I know, I'm streaming the file. Isn't this the right way to stream a binary file to a server? (thread for code)
    d
    • 2
    • 3
  • d

    dodalovic

    03/25/2022, 2:31 PM
    Hi, guys I'm trying to build a ktor 2.0 based native image, with CIO as an engine, and configured with the hocon file
    a
    • 2
    • 3
  • d

    dodalovic

    03/25/2022, 2:36 PM
    GraalVM 22.0.0.2 Java 11 CE
    • 1
    • 2
  • j

    John O'Reilly

    03/25/2022, 2:39 PM
    are there any examples of downloading a file using Ktor 2.x?
    d
    • 2
    • 5
  • d

    d.medina

    03/25/2022, 3:31 PM
    has anyone else seen this google is only providing me with vadge answers
    a
    • 2
    • 3
  • j

    Joey

    03/25/2022, 3:34 PM
    Are there any good examples on how to do streaming (body) uploads?
    a
    • 2
    • 1
  • t

    Tobias Gronbach

    03/26/2022, 10:13 AM
    Hi, having left my Ktor-Project (Ktor-Version 2.0.0-beta-1) untouched (and it was working just fine) for a while I came back and when I clicked "Run Server" I get the following exception and I have no idea what's going on? Any hint? Exception in thread "main" java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/ObjectMapper at com.auth0.jwk.UrlJwkProvider.<init>(UrlJwkProvider.java:80) at com.auth0.jwk.JwkProviderBuilder.build(JwkProviderBuilder.java:148) at de.tellsiggi.auth.config.jwt.JwtConfigKt.configure(JwtConfig.kt:31) at de.tellsiggi.ApplicationKt$module$1$1.invoke(Application.kt:34) at de.tellsiggi.ApplicationKt$module$1$1.invoke(Application.kt:33) at io.ktor.server.auth.jwt.JWTAuthKt.jwt(JWTAuth.kt:333) at io.ktor.server.auth.jwt.JWTAuthKt.jwt$default(JWTAuth.kt:329)
    a
    • 2
    • 3
  • g

    Grouvie

    03/27/2022, 1:46 PM
    Hi, I run my backend and frontend with ktor. The backend provides authorization routes and also serves my compose web page(s). Now I can not wrap my head around how to protect a page get request instead of a function.
    a
    • 2
    • 18
  • n

    Nathan Kleinschmidt

    03/27/2022, 3:05 PM
    I’m looking for help importing a gradle dependency from a github repo. It looks like I would clone the package code into my project and then reference it in my build.gradle.kts using
    implementation(files(./dependency))
    . My question is which path exactly do I need to reference?
    b
    • 2
    • 1
  • s

    S.

    03/27/2022, 4:14 PM
    I'm trying to test endpoints within a authenticate block which requires a UserSession but for some reason I can't get it to work with my /login-test route: Client request(GET http://localhost/login-test) invalid: 404 Not Found. Text: "" io.ktor.client.plugins.ClientRequestException: Client request(GET http://localhost/login-test) invalid: 404 Not Found. Text: ""
    testApplication {
                client.config {
                    install(HttpCookies)
                    install(ContentNegotiation) {
                        json()
                    }
                }
                routing {
                    get("/login-test") {
                        call.sessions.set(UserSession(id = 4))
                    }
                }
                client.get("/login-test")
                val response = client.get("v1/words")
                response.status shouldBe HttpStatusCode.OK
            }
    a
    • 2
    • 10
  • p

    phldavies

    03/28/2022, 10:36 AM
    With the ktor 2.0
    testApplication
    block, I’m trying to test some lifecycle hooks for a custom plugin. Is there a nice way to ensure the application environment is started than making a client call? I currently have something like this:
    private suspend fun ApplicationTestBuilder.ensureStarted() = client.get("/") { expectSuccess = false }
    
    class MyTest : FunSpec({
        test("plugin works correctly") {
            testApplication {
                install(MyCustomPlugin) { ... }
    
                ensureStarted()
    
                // test the plugin
            }
        }
    })
    a
    • 2
    • 7
  • d

    dodalovic

    03/28/2022, 12:08 PM
    Hi, I'd like to set some cookie as part of each authenticated call
    routing {
            authenticate("auth-jwt") {
                route("*") {
                   call.response.cookies.append(...)
                }
            }
           
            addRoutes()
        }
    is the way to go?
    s
    • 2
    • 2
  • a

    André Martins

    03/28/2022, 5:02 PM
    Hey when using
    HttpResponseValidator
    feature in ktor client how can I access original request information in
    handleResponseException
    is it possible in anyway?
    a
    • 2
    • 1
  • n

    natario1

    03/28/2022, 11:04 PM
    Hi, 2.0 question - with 1.X we’re able to upload an image as follows:
    contentType(ContentType.Image.JPEG)
    setBody(byteArray)
    But in 2.0, I get a 500 error. Has anything changed with respect to this?
    a
    • 2
    • 13
  • j

    James Black

    03/29/2022, 2:56 AM
    I am using 2.0.0-beta-1 and when I try to call with:
    val response: HttpResponse = <http://client.post|client.post>(
        "<https://example.com/login>"
    ) {
        contentType(ContentType.Application.Json)
        LoginModel(username, password).also { body = it }
    }
    l get this error on the body part: This API is internal in Ktor and should not be used. It could be removed or changed without notice. I attached a screenshot just to make certain it is clear. Basically, how can I set the body? I also tried body = LoginModel(...) but same error, same result. If I add the annotation to allow an internal API it works on Android but fails to compile on iOS. I am using Kotlin Multiplatform, with Kotlin 1.6.10 and kotlinxSerialization = "1.3.2" This is how I initialized the httpclient.
    fun createHttpClient() = HttpClient {
        install(ContentNegotiation) {
            json(Json { isLenient = true; ignoreUnknownKeys = true; useAlternativeNames = false; prettyPrint = true }
            )
        }
        install(Logging) {
            logger = Logger.DEFAULT
            level = <http://LogLevel.INFO|LogLevel.INFO>
        }
    }
    b
    • 2
    • 2
  • n

    Nikky

    03/29/2022, 2:44 PM
    can i "edit" the headers of a incoming request? i want to see if i can read a cookie and write it into a header so that some other feature / interceptor can work with it i get that i need to do somthing like
    receivePipeline.intercept(ApplicationCallPipeline.Features) {
        val headers = call.requestheaders
        
        //TODO: add header
    }
    but how would i copy the request or be able to get a mutable version of the headers ?
    s
    • 2
    • 2
Powered by Linen
Title
n

Nikky

03/29/2022, 2:44 PM
can i "edit" the headers of a incoming request? i want to see if i can read a cookie and write it into a header so that some other feature / interceptor can work with it i get that i need to do somthing like
receivePipeline.intercept(ApplicationCallPipeline.Features) {
    val headers = call.requestheaders
    
    //TODO: add header
}
but how would i copy the request or be able to get a mutable version of the headers ?
s

Satyam Agarwal

03/29/2022, 2:55 PM
You can instead, write an interceptor to read cookie header, find what you need and add it as an attribute to call.attributes map. And then your next feature/plug-in can find key and work with its value from call.attributes. I think that should work.
n

Nikky

03/29/2022, 2:57 PM
sadly i cannot modify the other feature too much (at least without significantly more effort) which is why i am trying to hack around it
View count: 3