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

    Goku

    04/13/2021, 12:25 PM
    Hello guys, I’m pretty new to KTOR and Kotlin in general… I’ve created a simple multiplatform project, and I’m calling the following endpoint from the iOS side:
    <https://api.github.com/projects/columns/42>
    in order to receive 401, which is intended. Unfortunately, the program crashes with the following explanation:
    Exception doesn't match @Throws-specified class list and thus isn't propagated from Kotlin to Objective-C/Swift as NSError.
    It is considered unexpected and unhandled instead. Program will be terminated.
    Uncaught Kotlin exception: io.ktor.client.features.ClientRequestException: Client request(<https://api.github.com/projects/columns/42>) invalid: 401 Unauthorized. Text: "{"message":"Requires authentication","documentation_url":"<https://docs.github.com/rest/reference/projects#get-a-project-column>"}"
    I get back the response and everything gets logged properly. Any idea on how to fix this? Thanks!
    r
    r
    • 3
    • 25
  • r

    Renaud

    04/13/2021, 3:52 PM
    It seems the new Ktor plugin (1.5.3) is only available for IntelliJ IDEA Ultimate. Do you think they plan on releasing it to the Community Edition ?
    🤯 1
    h
    • 2
    • 2
  • p

    Pablo

    04/13/2021, 6:44 PM
    Hello guys is there any way to add headers to all request in Ktor? I've tried to add them via
    buildHeaders { append("foo","bar" }
    but looks like is not working if I add them in the
    request
    it works... it's weird.
    httpClient.get<FooResponse>("<https://foo.bar>"){header("foo","bar")} <-- it works
    Any idea why?
    d
    o
    • 3
    • 8
  • p

    Pablo

    04/14/2021, 6:20 PM
    Is there any way to do a
    get
    inside a
    return HttpClient(OkHttp) {
      //For instance if I want to update a refreshToken
    }
    d
    j
    • 3
    • 9
  • c

    christophsturm

    04/14/2021, 9:08 PM
    can someone explain why this test fails:
    val context = describe("ktor") {
            it("routing works") {
                val server = TestApplicationEngine(environment = createTestEnvironment {
                    module {
                        routing {
                            route("/x") {
                                route("/y") {
                                    get {}
                                }
    
                            }
                        }
    
                    }
                }) {}.apply { start() }
    
                expectThat(server.handleRequest(HttpMethod.Get, "/x/y").response.status()).isNotNull().get { isSuccess() }.isTrue()
            }
        }
    d
    • 2
    • 3
  • j

    Justin Moy

    04/14/2021, 9:26 PM
    hi, we have a ktor http client trying to post to a ktor server with cookies. the server isn’t seeing any
    request.cookies[]
    , anyone have any idea why? setup in thread
    • 1
    • 2
  • o

    Osmium

    04/15/2021, 6:19 AM
    Does Ktor support reloading of existing routes? I.e. adding or removing them. If not, I can post a design ticket on YouTrack and try to implement that. Thank you.
    h
    • 2
    • 2
  • n

    Nikolay Kasyanov

    04/15/2021, 2:32 PM
    Hey folks 👋 I’m upgrading a project to ktor 1.5.3 and it breaks some tests when run on JVM (iOS tests are fine). In these tests, a class is tested that provides a reactive interface to its underlying
    HttpClient
    instance, by using Reaktive helpers to “convert” coroutines into
    Observable
    (or other Reaktive types). To do actual asserts, Reaktive helpers like
    TestObserver
    are used:
    fun `it does whatever a spider cat does`() {
        // ktorMockServerManager is just a way to configure mock engine handlers      
        ktorMockServerManager.enqueueRequest(
            ...
        )
    
        sut.doApiStuff(...)
            .test()
            .assertComplete()
    }
    The tests are completely synchronous, but as soon as I update ktor to 1.5.1 (1.5.0 is fine, though), they start failing because by the time
    assertComplete
    is called, the underlying coroutine hasn’t yet finished, so the tests fail. If I add a
    sleep
    call like this:
    fun `it does whatever a spider cat does`() {
    
        ktorMockServerManager.enqueueRequest(
            ...
        )
    
        val observer = sut.doApiStuff(...)
            .test()
    
        sleep(1000)
    
        observer.assertComplete()
    }
    I wonder what change between 1.4.3 and 1.5.1 could lead to this and what’s the way around it?
    👀 1
    e
    l
    • 3
    • 22
  • m

    MarkRS

    04/16/2021, 12:11 PM
    Is there some trick to getting logging working with multiplatform? I've followed the Ktor docs (https://ktor.io/docs/features-logging.html#configure_feature) but am getting nothing. My ktor client code is in commonMain, but I've tried delegating logging to an (Android) expected function, which is just a copy of the long logging experimental code, but still get nothing. I'm somewhat (ie very) stuck :(
    • 1
    • 1
  • f

    Fi5t

    04/16/2021, 4:17 PM
    Hi! Where can I find an exhaustive explanation about choosing between HOCON and Code configuration? I don't quite understand which way is more preferred.
    ➕ 1
    j
    m
    • 3
    • 6
  • g

    Guilherme Delgado

    04/17/2021, 9:42 AM
    Hi guys, I’m creating my first server that latter will be used in a KMP project. Question: how can I read values from, let’s say, a
    local.properties
    ? This was my idea:
    private fun getSecret(envKey: String, localKey: String): String = System.getenv(envKey) ?: ...(localKey,"")
    Thanks!
    b
    • 2
    • 3
  • p

    Pablo

    04/17/2021, 12:17 PM
    how can I do a network call inside a
    HttpClientConfig<OkHttpConfig>
    ? I need to refresh my credentials on my server if I get a 401
    y
    • 2
    • 1
  • n

    natario1

    04/18/2021, 2:47 PM
    Has anyone ever faced a websocket extension not being installed? I can see that
    install { }
    DSL is called, but the lambda passed to it is not. So that
    WebSocketExtensionFactory.install()
    is never called, and even the outer
    WebSocketExtensionsConfig.build()
    is never called.
    • 1
    • 1
  • a

    andrewreitz

    04/18/2021, 11:01 PM
    never mind I think I figured it out
    ❓ 3
    :rubber_duck: 1
    • 1
    • 1
  • x

    xxfast

    04/19/2021, 5:15 AM
    Hi all. Trying out
    ktor-client
    in Android, and running into this error whenever i’m trying to make any request
    kotlinx.coroutines.CoroutinesInternalError: Fatal exception in coroutines machinery for AwaitContinuation(DispatchedContinuation[Dispatchers.Main.immediate, Continuation at kotlinx.coroutines.DeferredCoroutine.await$suspendImpl(Builders.common.kt:101)@fcc4908]){Cancelled}@c6bb8a1. 
    ...
    at com.android.internal.policy.DecorView.superDispatchTouchEvent(DecorView.java:465)
    ...
    Caused by: java.lang.ClassCastException: kotlin.coroutines.jvm.internal.CompletedContinuation cannot be cast to kotlinx.coroutines.internal.DispatchedContinuation
    ...
    at io.ktor.util.pipeline.SuspendFunctionGun.access$resumeRootWith(SuspendFunctionGun.kt:15)
    Anyone got any clue as to what i’m doing wrong? I’m using Ktor
    1.5.2
    , with Android engine - along with kotlin
    1.4.30
    o
    • 2
    • 1
  • n

    Nikolay Kasyanov

    04/19/2021, 8:52 AM
    👋 Am I reading this right that I cannot pin to just root certificate, I have to pin to the whole chain in ktor? https://github.com/ktorio/ktor/blob/main/ktor-client/ktor-client-ios/darwin/src/io/ktor/client/engine/ios/certificates/CertificatePinner.kt
    y
    • 2
    • 7
  • d

    dave08

    04/19/2021, 3:34 PM
    Hi! Is this the way to set content type in tests (I thought there would be a better way?):
    private fun ContentType.full() = "$contentType/$contentSubtype"
    
    handleRequest(
            <http://HttpMethod.Post|HttpMethod.Post>, "/some-url") {
                addHeader(HttpHeaders.Accept, ContentType.Text.Plain.full())
            }
    h
    r
    • 3
    • 16
  • l

    landon burch

    04/19/2021, 8:39 PM
    in case it matters I am using kodein for dependency injection but I am not using within the test(in case that is part of the problem)
    • 1
    • 2
  • j

    Joost Klitsie

    04/19/2021, 10:18 PM
    Hello all! I have a question about multiple modules and Kodein: How can I import a Kodein.Module into every ktor module? 🙂 As I can only install a feature once, I would like to know how to add a Kodein modules per ktor module that I launch
    • 1
    • 4
  • d

    Dominick

    04/20/2021, 5:53 PM
    How can I generate a Java Keystore from an already made LetsEncrypt certificate that wasn't provided an alias on creation?
    l
    y
    • 3
    • 2
  • s

    stefandekanski

    04/21/2021, 11:45 AM
    Is there any reason not to make IosHttpRequestException an IOException ? It would be nice to make it so and also document (make the api contract) that
    HttpClient.request
    will throw
    IOException
    for IO errors… ?
    h
    • 2
    • 2
  • g

    Guilherme Delgado

    04/21/2021, 8:20 PM
    Hello, This is my configuration:
    //client
    HttpClient(Apache) {
        install(JsonFeature) { serializer = KotlinxSerializer(Json { ignoreUnknownKeys = true }) }
    }
    
    //server
    install(ContentNegotiation) {
            kotlinx.serialization.json.Json { ignoreUnknownKeys = true }
    //        gson { setPrettyPrinting() }
        }
    and this is a sample request:
    val response = client.get<List<Event>>("<http://localhost:8080>${application.locationToUrl(EventsApi())}") {
        body = ...
        contentType(ContentType.Application.Json)
    }
    and this is the output:
    invalid: 415 Unsupported Media Type. Text: ""
    But if I uncomment
    gson { setPrettyPrinting() }
    it works… Shouldn’t
    kotlinx.serialization.json.Json
    be enough? 🤔
    r
    • 2
    • 4
  • d

    Dominick

    04/22/2021, 4:54 AM
    How can I make it so I host the website & the backend in the ktor app. I was thinking of static content and then XMLHTTPRequest to access the backend api: ktor app +----------- / -> public/index.html (has assets that also need to be accessible from the /public folder) /security -> public/security.html (has assets that also need to be accessible from the /public folder) /api -> handled by the api using GET, POST, etc. functions How should my routes look? EDIT: I tried this but it didn't really work. /api returned correctly but / and /index.html or any other asset in /public did not show up.
    get("/api") {
                call.respondText("works")
            }
    
            static {
                resource("/", "public/index.html")
                resource("*", "public/index.html")
                resources("public")
            }
    h
    • 2
    • 7
  • h

    Harry B

    04/22/2021, 10:12 AM
    Does the KTor client support windows with K/N ?
    :yes: 1
    m
    • 2
    • 2
  • c

    coder82

    04/22/2021, 10:16 AM
    The ktor http client doesn't seem to allow to bind the http request to a different ip on the network interface, apache http client allows it by specifying a different local address from the request builder, is there a way to do it in ktor http client? Even using the Apache http client there seems to be no control over this.
    • 1
    • 2
  • d

    darkmoon_uk

    04/22/2021, 1:46 PM
    I just found out that Ktor is leaking memory like a sieve in my Kotlin/Native Application. Is there anything I can do about this? My App makes HTTP request every 5 seconds on average; it's necessarily chatty, so the leaks add up very quickly and cause the App to be force quit by iOS within an hour. Seeing this: https://youtrack.jetbrains.com/issue/KTOR-1238 ...I have ensured that HttpClient is not being recreated, a couple of instances are being reused. But HttpResponse is probably the one being leaked and I see no solution.
    d
    • 2
    • 1
  • r

    Raed Ghazal

    04/22/2021, 5:53 PM
    Hi, any ideas how to import Ktor plugin to intelliJ IDEA? in the plugins market there's a Ktor (Obsolete) which looks like not the supported version. and on the website I downloaded the Ktor lib which contains ktor-plugin.jar, resources_en.jar, but can't find a way to import both
    s
    h
    • 3
    • 37
  • t

    Tim Malseed

    04/23/2021, 12:38 AM
    Hi all, I'm looking to run my Ktor development environment inside a Docker container. Ideally, I wouldn't necessarily be packaging the app for deployment whenever I make a code change. Instead, I imagine the source code existing on the host machine, and then the classes/files required to run the development environment will be volume mounted into the Docker container. The trouble I have is I don't actually understand what the IDE does when you 'run' a Ktor project in the IDE. What commands are invoked? Is it possible to replicate this process manually, within the Docker container? This is less a question about Docker and more about compiling/running a Ktor application from a shell.
    h
    • 2
    • 4
  • l

    landon burch

    04/23/2021, 5:00 PM
    I am trying to mock a database within my unit test. This doesn't work currently because in my test I am using the
    withTestApplication({ module() })
    inside the module it setup database with url does doesn't point anywhere.. I wanted to know if anyone had experience with this. I am hoping to keep this a mock and not an in memory database..
    f
    • 2
    • 2
  • a

    Alexander Black

    04/23/2021, 6:00 PM
    Hey, I’m wondering is there a way to use the Ktor sterilization system to sterilize a third party java object into JSON? Or do you have to create a data object and transfer to that? I’ve been hunting around the internet quite a bit looking for some solution. Any help with this would be greatly appreciated.
    t
    • 2
    • 2
Powered by Linen
Title
a

Alexander Black

04/23/2021, 6:00 PM
Hey, I’m wondering is there a way to use the Ktor sterilization system to sterilize a third party java object into JSON? Or do you have to create a data object and transfer to that? I’ve been hunting around the internet quite a bit looking for some solution. Any help with this would be greatly appreciated.
t

turansky

04/23/2021, 6:26 PM
https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/serializers.md#custom-serializers?
👍 1
🙌 1
a

Alexander Black

04/23/2021, 6:56 PM
@turansky thank you! this looks great! I stumbled on that doc before, but I was not sure if it was what I was looking for.
🚀 1
View count: 3