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

    guenther

    05/31/2019, 5:19 AM
    Hi, I'm not too much into Ktor jet (even if I already created one or two projects with it), and just wanted to ask some general question about the idea behind Ktor: (let's ignore the client part for this question): Is Ktor a Framework for HTTP communication only or should it more seen as a generic way of building server applications? So should it also be possible (in the future) e.g. to build a server application listening on RabbitMQ completely independent of HTTP?
    c
    m
    • 3
    • 4
  • r

    rapho

    05/31/2019, 11:27 AM
    Hey, how can I install a feature if my main class is not of type io.ktor.application? I'm using Java 9.
    c
    m
    • 3
    • 11
  • r

    robstoll

    05/31/2019, 2:56 PM
    is it just for me or does the example here not work: https://ktor.io/clients/http-client/testing.html
    r
    • 2
    • 17
  • m

    Michael Strasser

    06/01/2019, 7:31 AM
    Hello! I have created a Ktor feature https://github.com/mjstrasser/ktor-features-zipkin/ that enables a Ktor app to participate in Zipkin distributed tracing. The code includes a server feature that recognises Zipkin HTTP tracing headers and a client feature that propagates headers into downstream calls. Let me know what you think, and whether it is useful to you.
    👏 6
    s
    m
    • 3
    • 2
  • m

    mantono

    06/03/2019, 9:39 AM
    I have read https://ktor.io/advanced/pipeline.html but I am still a bit lost when it comes to how to control exactly when a Feature is run. I have a feature that should be run after authentication (I want to check if a principal is present) but before it is too late to make a
    call.respond(...)
    . It seems that whenever I insert my feature to a
    PipelinePhase
    it is either too early for the principal to have been processed (I can see for example that the
    Authorization
    header is present, but
    principal
    is null because it has not been set yet) or to late to make a response to the request. How do I solve this (in a good manner)?
    • 1
    • 1
  • a

    Andy Victors

    06/03/2019, 10:59 AM
    By default, Ktor HTTP client does follow redirections; this feature allows to follow Location redirects in a way that works with any HTTP engine.
    vs
    The iOS engine uses the asynchronous NSURLSession internally. And have no additional configuration.
    What is right? I use
    followRedirects=false
    in MPP common code and on android it works properly but obviously it still follows redirects on iOS. Any way possible to force ktor not to follow redirects on iOS?
    e
    • 2
    • 4
  • a

    Andrew Gazelka

    06/03/2019, 11:02 PM
    <http://httpClient.ws|httpClient.ws>(...)
    does not propagate errors... is there any way to catch them?
    d
    e
    • 3
    • 4
  • r

    ribesg

    06/05/2019, 8:27 AM
    Why can’t I set the content type on a request? It fails saying the engine should handle the content type header, what does that mean?
    e
    • 2
    • 13
  • r

    ribesg

    06/05/2019, 8:58 AM
    Found a small issue, this doesn’t work when using okhttp3 engine:
    <http://http.post|http.post>(url) {
                body = EmptyContent
            }
    👀 1
    e
    • 2
    • 5
  • d

    darkmoon_uk

    06/06/2019, 10:04 PM
    How does one post an object via
    HttpClient
    that should be Json Encoded? Using iOS, if that matters, and I have the
    JsonFeature
    installed... but I get
    kotlin.ClassCastException: example.model.Person cannot be cast to io.ktor.client.call.HttpClientCall
    . Here's my code:
    runBlocking {
                val client = HttpClient()
    
                val message = <http://client.post|client.post><Person> { //(path = "/path") {
                    url("<http://localhost:8080/path>")
                    contentType(ContentType.Application.Json)
                    body = Person("James", "Smith")
                }
            }
    ...
    Person
    is
    @Serializable
    , should I not be setting it to the body of the post request like this? I assumed that, being
    Any
    ,
    JsonFeature
    would know how to handle this? Can't find an example or details in ktor documentation.
    m
    • 2
    • 1
  • o

    oday

    06/07/2019, 5:11 PM
    and besides, with the settings like in the docs, you dont need that http client, you can use embeddedserver and that’s it, they dont even initialize that instance, the one that lights up red
    o
    • 2
    • 4
  • o

    orangy

    06/08/2019, 4:21 PM
    Yes, do a safe cast
    call as? RoutingApplicationCall
    . If it’s not null, you’re in a route handler (or interceptor) and you can get route from there. However, you need to place interceptor inside
    routing
    for this to work
    🙏 1
    m
    • 2
    • 4
  • d

    darkmoon_uk

    06/09/2019, 1:30 AM
    kotlin.NoSuchElementException: List is empty
    when initialising
    HttpClient
    with
    JsonFeature
    on iOS 🤔 Not sure what's going wrong here but I suspect I have the wrong dependencies for target
    iosMain
    , being:
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core-iosx64:$kotlin_coroutines_version")
                    implementation("org.jetbrains.kotlinx:kotlinx-serialization-runtime-native:$kotlin_serialization_version")
                    implementation("io.ktor:ktor-client-ios:$ktor_version")
                    implementation("io.ktor:ktor-client-json-iosx64:$ktor_version")
    ..it's hard to follow what the dependencies should be from Ktor documentation and examples. These don't seem to have kept pace with recent changes in meta-data driven identifiers and other refactoring.
    Ktor_w__JSON_Feature_on_iOS__crash.txt
    👀 1
    r
    • 2
    • 7
  • p

    pawelbochenski

    06/10/2019, 12:16 PM
    Hi, does anyone know how to make something androids like BuildConfig.Debug but in ktor? I'm using gradle with groovy
    g
    r
    • 3
    • 5
  • m

    Marc Knaup

    06/12/2019, 12:26 AM
    Let's start a thread on how to use Ktor
    HttpClient
    in a
    Worker
    (background thread) on native 🙂
    👀 1
    e
    • 2
    • 6
  • d

    Dico

    06/12/2019, 5:46 AM
    Does anyone else get this error regularly?
    • 1
    • 1
  • g

    guenther

    06/14/2019, 9:10 AM
    Maybe someone has already done this? Could someone help me a little bit? Then I'd be glad to make a PR for the ktor-examples on Github to have this there as well for the future.
    b
    • 2
    • 5
  • t

    twisterrob

    06/14/2019, 9:27 AM
    Hey, I have an interesting challenge. I want to write a single-use web server. That is: create a Kotlin function that launches an embedded server, waits for a request and returns data from that request after stopping the server. The problem is blocking the function (the one that does embeddedServer) return until the request comes in, since routed
    get
    is deep in the DSL. I wonder what primitives you would suggest me to use to do the blocking.
    r
    • 2
    • 5
  • a

    Andy Victors

    06/14/2019, 1:31 PM
    Will cookies be properly processed if I do not specify
    install(HttpCookies) {
                storage = AcceptAllCookiesStorage()
            }
    on client init? Specifying this causes iOS MPP to crash, but I need cookies! ;/ P.S. Also I cannot extract it from headers directly 'cause it looks like ktor strips the "Set-Cookie" header before 😕
    🤔 1
    👀 1
    e
    • 2
    • 5
  • d

    darkmoon_uk

    06/16/2019, 1:16 AM
    Is it always necessary to install the
    ContentNegotiation
    feature in the server to receive & send serialized (JSON encoded) objects? If the expected, exact content type is specified on both server and receiver, I don't see why
    ContentNegotiation
    needs to be a hard requirement - I thought this was only about dynamically negotiating a variable content & type at run-time?
    d
    • 2
    • 2
  • m

    mbonnin

    06/16/2019, 3:49 PM
    What would be an idiomatic way to handle refreshing oauth tokens on demand using ktor-client ? i.e. the equivalent of this kind of okhttp things: https://gist.github.com/alex-shpak/da1e65f52dc916716930
    b
    • 2
    • 5
  • e

    Evan Bennett

    06/17/2019, 1:11 AM
    I am trying to setup my ktor session cookie to contain a session UUID and the locale for the user. I have to following in `fun io.ktor.application.Application.main()`:
    install(Sessions) {
    		val sessionCookieKey = io.ktor.util.hex(environment.config.property("ktor.session.cookie.key").getString())
    		fun configureCookie(): CookieSessionBuilder<*>.() -> Unit = {
    			cookie.duration = null
    			cookie.domain = null
    			cookie.path = "/"
    			cookie.secure = true
    			cookie.httpOnly = true
    			cookie.extensions["SameSite"] = "Strict"
    			transform(SessionTransportTransformerMessageAuthentication(sessionCookieKey))
    		}
    		cookie<my.type.UuidV4>("SESSION_UUID", configureCookie())
    		cookie<java.util.Locale>("LOCALE", configureCookie())
    	}
    I am getting an exception when I make a request to the server. (Which I will post as a reply.) After looking in to this for a while, it appears that the
    SessionSerializerReflection.properties
    contains
    [var java.util.Locale.baseLocale: sun.util.locale.BaseLocale!, var java.util.Locale.localeExtensions: sun.util.locale.LocaleExtensions!, var java.util.Locale.hashCodeValue: <http://kotlin.Int|kotlin.Int>, var java.util.Locale.languageTag: kotlin.String!]
    which are all
    private transient
    members of the
    java.util.Locale
    class. Is this a bug, or should I be doing this differently?
    • 1
    • 2
  • e

    Edd

    06/17/2019, 2:26 PM
    Hello, I'm working with
    HttpClient
    which executes a long request. This call is triggered via a
    post
    route, which looks something like this:
    val http = HttpClient(Apache)
    
    routing {
        post("/api/start-job") {
            <http://http.post|http.post><String>("<http://url-to-long-request>")
            call.respond(HttpStatusCode.Accepted, "job started")
        }
    }
    Sending a request to this route results in having to wait quite as the client makes a heavy request (it starts a job on another service). I'd like to simply send the request to
    <http://url-to-long-request>
    and immediately return the
    202
    with
    "job started"
    message. I could achieve this using an
    Executor
    and wrapping the
    <http://http.post|http.post>
    call, however I feel like that is not the right way to do this. Any suggestions on this?
    r
    u
    • 3
    • 8
  • t

    tjohnn

    06/17/2019, 7:34 PM
    Am I missing something? Any help is appreciated
    • 1
    • 1
  • v

    voben

    06/17/2019, 7:39 PM
    Might be related to pulling out request values from
    call
    t
    • 2
    • 2
  • d

    Darren Bell

    06/17/2019, 11:23 PM
    On the javascript side I am getting a similar error to someone earlier when using the HttpClient getting
    List is empty.", cause_th0jdv$_0: null, name: "NoSuchElementException"
    My gradle file has the following
    compile ("org.jetbrains.kotlinx:kotlinx-serialization-runtime-common:${LibraryVersions.kotlin_js_serialization_version}")
        compile ("org.jetbrains.kotlinx:kotlinx-serialization-runtime-js:${LibraryVersions.kotlin_js_serialization_version}")
        compile ("io.ktor:ktor-client-core:${LibraryVersions.ktor_version}")
        compile ("io.ktor:ktor-client-js:${LibraryVersions.ktor_version}")
        compile ("io.ktor:ktor-client-json-js:${LibraryVersions.ktor_version}")
        compile ("io.ktor:ktor-client-serialization-js:${LibraryVersions.ktor_version}")
        compile ("io.ktor:ktor-client-auth-basic-js:${LibraryVersions.ktor_version}")
    Has anyone managed to get this working?
    e
    • 2
    • 4
  • y

    yshrsmz

    06/18/2019, 10:54 AM
    @e5l Hi, can you provide some more detail on this? I'm facing this error, but unable to resolve for now.
    install(HttpCookies) {
      storage = CustomStorage()
    }
    above code does not work, as
    AcceptAllCookiesStorage
    is provided as a default value for Config class. https://kotlinlang.slack.com/archives/C0A974TJ9/p1560522327059700?thread_ts=1560519079.059100&amp;cid=C0A974TJ9
    e
    a
    • 3
    • 6
  • j

    Johnroest

    06/19/2019, 1:09 PM
    Anyone knows how to handle that?
    e
    p
    • 3
    • 7
  • v

    vngantk

    06/20/2019, 12:51 AM
    How can I get the X509 client certificate from an HTTPS request like what I can do with the servlet framework using HttpServletRequest.getAttribute(“javax.servlet.request.X509Certificate”)?
    c
    j
    • 3
    • 3
  • t

    tjohnn

    06/20/2019, 11:19 AM
    How can I get the handle to the specific exception that’s being handled by StatusPages exception(){}?
    c
    • 2
    • 3
Powered by Linen
Title
t

tjohnn

06/20/2019, 11:19 AM
How can I get the handle to the specific exception that’s being handled by StatusPages exception(){}?
c

cy

06/20/2019, 11:37 AM
it
application.install(StatusPages) {
            exception<NotImplementedError> { error ->
                call.respondHtml(HttpStatusCode.NotImplemented) {
...
t

tjohnn

06/20/2019, 11:54 AM
Thanks. I was overthinking it.
View count: 1