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

    mazorius

    12/09/2020, 10:28 PM
    Hi, I try to write in a Gradle task an post of a artifact.
    HttpClient().use {
          GlobalScope.launch {
            it.submitFormWithBinaryData {
              url {
                url(artifactRepository.get().baseUrl.clone().build())
    
                parameter("repository", repositoryName.get())
    
                headers {
                  append("User-Agent", System.getProperty("os.name"))
                }
              }
            }
          }
        }
    Unfortunately this ends up in the second run with
    io.ktor.client.engine.ClientEngineClosedException: Client already closed
    Anyone an idea how I can handle this?
    • 1
    • 1
  • s

    Shreyas Patil

    12/10/2020, 11:42 AM
    If we're developing a big scale application with Ktor in which there might be many modules. Which DI framework is recommended to use? I saw Kodein, Koin, etc. But they uses reflection I guess which might affect performance? I can use Dagger but it not looks good solution in Ktor since everything here is in functions in Ktor. Any suggestion for choosing right DI Framework? My question might be wrong because I'm not from backend development. I've used DI in Android a lot so just want to see how it can be used here
    👀 1
    j
    a
    +3
    • 6
    • 21
  • c

    christophsturm

    12/10/2020, 3:56 PM
    idea seems to not find source jars for ktor jars. when i click on a stacktrace line thats from a ktor jar i see decompiled code instead of the ktor source.
    ☝️ 1
    • 1
    • 3
  • c

    christophsturm

    12/10/2020, 4:32 PM
    I think ktor is really lacking in error handling. for example if you send a json body with one misspelled field it just returns 500 without any useful information (i made a pr to fix this). or when you send a jwt token in a wrong format (“Bearer: <token>” instead of “Bearer <token>“) it logs 2 stacktraces with the error message “java.lang.IllegalArgumentException: invalid authScheme value: it should be token”
    h
    • 2
    • 3
  • e

    Evan

    12/10/2020, 7:34 PM
    Hey all, I’m using ktor in a KMP project that mainly interacts with a .NET server. All of the API operations are using content type
    application/json
    and the KotlinX serializer / JsonFeature, except for one. On one endpoint, I have to upload file content with a
    multipart/form-data
    request, that expects an
    application/json
    response. When I try to set the header on that request, it gives an error that the ktor engine is supposed to control the content type. Is there a way to override that behavior, or will I have to create a new HttpClient without the JsonFeature installed?
    • 1
    • 2
  • n

    Nikky

    12/11/2020, 11:53 AM
    can i create a HttpClient based on a existing one? similar to
    Json(Json.Default) { /*config here*/ }
    r
    • 2
    • 2
  • b

    bod

    12/11/2020, 3:27 PM
    Hello, World! Hey using Ktor HttpClient in a native project has been painful to me for the last few releases. Currently I'm experiencing
    Frozen during lazy computation
    when using
    by lazy
    and
    InvalidMutabilityException: mutation attempt of frozen (my class)
    when not. I must admit I still haven't understood what "frozen" mean... All works well with the same code on the JVM. Am I the only one?
    e
    • 2
    • 2
  • a

    Arkangel

    12/11/2020, 5:28 PM
    seen this.. but it don’t work
    FuelManager.instance.addRequestInterceptor(tokenInterceptor())
    fun tokenInterceptor() = {
        next: (Request) -> Request ->
        { req: Request ->
            req.header(mapOf("Authorization" to "Bearer AbCdEf123456"))
            next(req)
        }
    }
    n
    • 2
    • 1
  • t

    tieskedh

    12/14/2020, 1:26 PM
    Question: probably it's a real rare use-case, so I get it if it's not supported. I'm using a single class for my client-tests. By expanding it a tiny step every time a test needs something more, it is gradually becoming smarter. (this way mocks can become the real deal). My question is: is it possible to connect the MockEngine of the client with a server in a way that it doesn't create the web-server itself?
    n
    • 2
    • 2
  • c

    czuckie

    12/16/2020, 4:23 PM
    I hope explanations on how to unit test ktor projects are going to be added to the documentation, or even better yet, to the quick start project structure - it's incredibly difficult to dip into ktor without it being easy to unit test 😞
    m
    j
    • 3
    • 2
  • a

    Andrey Nikanorov

    12/17/2020, 2:51 PM
    Hello!
    HttpResponseValidator
    does not work on JS target for me. Any ideas?
    validateResponse
    is not called at all. Everything works as expected on Android (the same code). Bug or I miss something? 1.4.2
    • 1
    • 1
  • p

    Peter Ertl

    12/17/2020, 3:45 PM
    what is the correct way to render a “HTTP 204 No Content” response in ktor? The problem seems so easy but I can’t find any non-trivial solution to it.
    m
    • 2
    • 11
  • m

    Md Hanif

    12/18/2020, 2:12 PM
    Hi folks. I am new to KMM and trying to create a generic function for api calling using ktor with 
    reified
      and it seems to work fine with 
    android
     but throws an error in 
    iOS
    This is my common api call return in Shared file.
    @Throws(Exception::class)
    suspend inline fun<reified T> post(url: String, requestBody: HashMap<String, Any>?) : Either<CustomException, T> {
        try {
            val response = <http://httpClient.post|httpClient.post><T> {
                url(BASE_URL.plus(url))
                contentType(ContentType.Any)
                if (requestBody != null) {
                    body = requestBody
                }
                headers.remove("Content-Type")
                headers {
                    append("Content-Type", "application/json")
                    append("Accept", "application/json")
                    append("Time-Zone", "+05:30")
                    append("App-Version", "1.0.0(0)")
                    append("Device-Type", "0")
                }
            }
            return Success(response)
        }  catch(e: Exception) {
            return Failure(e as CustomException)
        }
    }
    It works good in android if I call it like this :-
    <http://api.post|api.post><MyDataClassHere>(url = "url", getBody()).fold(
        {
            handleError(it)
        },
        {
            Log.d("Success", it.toString())
        }
    )
    But I am not able to get it run on iOS devices it shows me error like this :- `some : Error Domain=KotlinException Code=0 "unsupported call of reified inlined function `com.example.myapplication.shared.apicalls.SpaceXApi.post`" UserInfo={NSLocalizedDescription=unsupported call of reified inlined function
    <http://com.example.myapplication.shared.apicalls.SpaceXApi.post|com.example.myapplication.shared.apicalls.SpaceXApi.post>
    , KotlinException=kotlin.IllegalStateException: unsupported call of reified inlined function
    <http://com.example.myapplication.shared.apicalls.SpaceXApi.post|com.example.myapplication.shared.apicalls.SpaceXApi.post>
    , KotlinExceptionOrigin=}` Any help in this is  appreciated. Thanks
    m
    j
    • 3
    • 20
  • i

    Ivan

    12/21/2020, 11:25 AM
    Hi everybody, There is a way to understand if a route is under auth from his parent tree?
    e
    h
    • 3
    • 4
  • r

    rsetkus

    12/21/2020, 9:23 PM
    Hi. As far as I can understand Ktor features are split into separate libraries. What is the way to find out exact gradle dependency of a feature? Documentation doesn’t mention it.
    l
    d
    • 3
    • 8
  • h

    hhariri

    12/22/2020, 8:36 AM
    **************************** Ktor 1.5.0 Released* ***************************** https://blog.jetbrains.com/ktor/2020/12/22/ktor-1-5-0-released/
    🎉 37
    j
    a
    +2
    • 5
    • 19
  • j

    Justin Moy

    12/22/2020, 8:19 PM
    i’m trying to do some async processing in the scope of a ktor web request, our server is expecting to receive a payload and upon receiving the payload, the server is supposed to return a http 200 immediately and then do some processing on the payload (which will involve making some API calls), any ideas on how to best do this in a ktor app?
    n
    j
    • 3
    • 9
  • r

    Robert Jaros

    12/23/2020, 1:27 AM
    Yesterday I've struggled with problems with Jackson deserializer and sealed classes when running Ktor from gradle task. Today I've upgraded to 1.5.0 and the problem is still there, but only when I enable development mode. With the default (dev mode off) the problem is gone. What does this new development mode really do?
    c
    • 2
    • 2
  • m

    Marc Knaup

    12/23/2020, 3:17 PM
    What is the reason I have to manually
    close()
    an
    HttpClient
    ? Why isn’t it designed so that the
    HttpClient
    is bound to a
    CoroutineScope
    and automatically closes when the scope is canceled/completed? Isn’t this breaking structured concurrency (or at least requires workarounds)?
    👀 2
    j
    a
    • 3
    • 5
  • n

    n8ebel

    12/23/2020, 9:06 PM
    Has anyone tried enabling/disabling the new 1.5 development mode when running from the command line via the gradle wrapper? I’ve successfully done it via the
    application.conf
    file by setting
    development=true
    . And by adding
    -Dio.ktor.development=true
    to VM options in the IntelliJ run configuration But no luck from the command line so far.
    d
    • 2
    • 1
  • h

    Hamza

    12/24/2020, 12:25 PM
    Hey guys, is the ktor website open source? Maybe I'm not looking hard enough but I can't find it in the ktor repo. I wanted to add something to one of the doc pages but can't figure out where I should do that 😕
    d
    • 2
    • 5
  • j

    Jgafner

    12/25/2020, 12:43 PM
    Hi all 👋🏻 - I have a small beginner question: I am writing an API service that support some GET/POST and in turn it create rest call to fetch the data from different sources (dB , and other services) So any built in / suggested framework to implement the API calls I need to do in my services? I used to work with OKHTTP3 but I though maybe there are some default for ktor. Tnx
    d
    • 2
    • 2
  • m

    Matthieu Stombellini

    01/03/2021, 12:04 AM
    Hi, I need to test my custom feature, and for this I need to change the
    remoteHost
    value, but it looks like it's hardcoded in
    TestApplicationRequest.local
    . How can I set it to a custom value? The technique
    ForwardedHeaderSupport
    uses to have a mutable version of
    RequestConnectionPoint
    is internal I also can't use the already existing MutableOriginConnectionPoint, as it's deprecated
    m
    • 2
    • 2
  • r

    Roman Vasilyev

    01/03/2021, 9:29 PM
    hi, want to join ktor ios websockets development, how I can do it?
    c
    • 2
    • 23
  • t

    tieskedh

    01/04/2021, 10:22 AM
    Don't know if this is the correct place to ask, but is there a download-manager for common Kotlin?
    a
    • 2
    • 3
  • m

    maxmello

    01/05/2021, 5:39 PM
    Ktor 1.5 changed the trailing slashes behavior, which is fine / good, but this here does not appear to work:
    route("/resource") {
       get("/") {
      ...
    If i call GET /resource/, I get a not found. /resource works
    route("/resource/") {
       get {
       ...
    In this case, GET /resource/ is found, but /resource not (expected behavior) Is this intended behavior, a bug, or am I missing something?
    r
    • 2
    • 2
  • r

    Roman Vasilyev

    01/06/2021, 5:52 AM
    in ktor 1.5
    expectSuccess
    stopped working, 1.4.3 triggered
    validateResponse
    on 404 e.t.c, now not:
    fun HttpClientConfig<*>.myInit() {
        expectSuccess = false
        addMyValidator()
    }
    
    fun HttpClientConfig<*>.addMyValidator() {
        HttpResponseValidator {
            validateResponse { response ->
            }
        }
    }
    r
    c
    • 3
    • 13
  • j

    jozefdransfield

    01/06/2021, 11:09 AM
    I have an issue where a request is generating an exception io.ktor.utils.io.charsets.MalformedInputException: Input length = 1, In the request handler i am doing call.receiveParameters() which i think is where the issue is coming from. However my issue is how can i capture the raw request as this is happening in the wild and i want to capture the body in a log so i can investigate?
    r
    • 2
    • 14
  • i

    igor.wojda

    01/06/2021, 1:09 PM
    Hey. I am playing with ktor and I am running a server with netty. I wonder what is the best way to debug such application? I can set breakpoints and this is fine, but I need to understand whats going on - i need more visibility to know why ny server returns 500 ? Can we print stack trace and crash the app instead of returning 500?
    t
    • 2
    • 5
  • t

    tim

    01/06/2021, 5:06 PM
    Hi folks, i'm trying to get my simple websocket client to work with ktor 1.5.0 and the cio engine. When I run it locally I have no issues, but when its bundled inside a jib built docker container (adopt open jdk 14) its hanging:
    suspend fun connect(host: String, path: String): DefaultClientWebSocketSession {
        val client = HttpClient { install(WebSockets) }
        println("I execute")
        val session = client.webSocketSession {
            url("wss", port = 443, host = host, path = path)
                println("I execute")
            }
            println("I don't execute")
            return session
        }
    }
    Any thoughts?
    • 1
    • 6
Powered by Linen
Title
t

tim

01/06/2021, 5:06 PM
Hi folks, i'm trying to get my simple websocket client to work with ktor 1.5.0 and the cio engine. When I run it locally I have no issues, but when its bundled inside a jib built docker container (adopt open jdk 14) its hanging:
suspend fun connect(host: String, path: String): DefaultClientWebSocketSession {
    val client = HttpClient { install(WebSockets) }
    println("I execute")
    val session = client.webSocketSession {
        url("wss", port = 443, host = host, path = path)
            println("I execute")
        }
        println("I don't execute")
        return session
    }
}
Any thoughts?
I've had the same issue with ktor 1.4.x
I've tried it against two different websocket severs ... The first screenshot is where it hangs when running inside docker. And the 2nd is where it successfully connects when running on my linux machine.
Successful connection:
Tried downgrading to ws and it connects successfully then 🤔 🤷
Hmm it appears to be something with my network or my laptop/os 😞
Update on this in case anyone else runs into the same issue. The container i'm using is a minimal alpine container for the jre ... which doesn't install ca certificates by default and so web sockets cannot verify the server and it hangs. Would be great if there was a better error message! Anyways the fix is simply to add the certificates to the container.
View count: 3