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

    galex

    02/15/2019, 5:09 AM
    While trying to upload files and the file is a little big (>700KB) from kotlin-react with ktor-client I still hit a buffer limit:
    "IllegalArgumentException: should should be greater than write space + end gap (size = 9, writeRemaining = 0, endGap = 8, rem+gap = 8
        at IllegalArgumentException_init_0 (<http://localhost:9000/bundle.js:162304:32>)
        at require$ObjectLiteral_1.doFail (<http://localhost:9000/bundle.js:34344:9>)
        at IoBuffer.writeBufferAppend_ehtrw3$ (<http://localhost:9000/bundle.js:35661:7>)
        at ByteReadPacket_0.ByteReadPacketBase.prepareRead_87ik6q$ (<http://localhost:9000/bundle.js:31628:10>)
        at ByteReadPacket_0.ByteReadPacketBase.readAsMuchAsPossible_v6e8td$_0 (<http://localhost:9000/bundle.js:31444:15>)
        at ByteReadPacket_0.ByteReadPacketBase.readAsMuchAsPossible_v6e8td$_0 (<http://localhost:9000/bundle.js:31455:19>)
        at ByteReadPacket_0.ByteReadPacketBase.readAsMuchAsPossible_v6e8td$_0 (<http://localhost:9000/bundle.js:31455:19>)
        at ByteReadPacket_0.ByteReadPacketBase.readAsMuchAsPossible_v6e8td$_0 (<http://localhost:9000/bundle.js:31455:19>)
        at ByteReadPacket_0.ByteReadPacketBase.readAsMuchAsPossible_v6e8td$_0 (<http://localhost:9000/bundle.js:31455:19>)
        at ByteReadPacket_0.ByteReadPacketBase.readAsMuchAsPossible_v6e8td$_0 (<http://localhost:9000/bundle.js:31455:19>)"
    I post via
    client.submitForm {}
    and I’ve tried
    submitFormWithBinaryData {}
    as well, no differences 😞
    e
    • 2
    • 8
  • t

    tjb

    02/17/2019, 12:01 AM
    seems to be happening because of
    val client = HttpClient() {
        install(BasicAuth) {
          username = "test"
          password = "pass"
        }
        install(JsonFeature) {
          serializer = GsonSerializer()
        }
      }
    b
    • 2
    • 4
  • a

    AllowFlame

    02/18/2019, 3:28 AM
    Hi, all. I got some trouble with ktor. I made java lib(jar) which include following code. And I call the function in SpringBoot project. Compilation is ok but when it is called, I got “java.lang.ClassNotFoundException: io.ktor.client.HttpClientJvmKt” error. What’s should I do?
    -.kt
    e
    • 2
    • 2
  • j

    Jonathan Mew

    02/18/2019, 10:53 AM
    Hi, we are working on an offline-first app that may be run on shared computers and are trying to put together a sensible session management process. We'd initially used the out-of-the-box cookie-based sessions setup and an HttpOnly cookie to mitigate the risk of session hijacking via XSS. However this poses a problem because when the user's session expires while they are offline, it makes it impossible to clear down that cookie programatically. To solve this, we'd like to set up sessions based on one HttpOnly cookie and one that is accessible to JavaScript as a kind of composite key, and we're trying to gauge how much of the ktor sessions code we will be able to reuse and how much we would need to implement. That will enable us to clear one of the cookies to kill the session even while the user is offline, but we still get the benefits of the HttpOnly cookie while they are online. Our understanding is that the existing cookie() feature expects to deal with only a single cookie. Also Sessions.Configuration is not an open class so we cannot create our own implementation there, which means we probably can't use the existing feature at all, and would need to reimplement most of the cookie session handling code. Is that correct? Perhaps you have a better approach for how to handle an offline logout - we'd certainly be interested!
    m
    • 2
    • 3
  • d

    dewildte

    02/19/2019, 3:10 PM
    Is there a good example of unit testing MPP Ktor client using serialization with
    MockEngine
    ?
    r
    t
    • 3
    • 10
  • a

    alexfacciorusso

    02/20/2019, 11:17 AM
    Hi guys! I'm trying to create a Feature that will wrap the end result of the various parsing engines (JsonFeature etc...) to a custom Response class. What's the best way of doing it? e.g. I want to be able to do
    httpClient.get<Result<MyApiResponseType>>(...)
    and getting a result object that will contain its success/fail state, the exception etc.
    b
    • 2
    • 2
  • z

    ziad

    02/20/2019, 3:29 PM
    Hi everyone, has anyone had success using Ktor as a real-time backend for a game? Does that sound like a reasonable undertaking or would things like scaling be too cumbersome to deal with?
    m
    • 2
    • 5
  • k

    kevin

    02/20/2019, 8:03 PM
    I’m trying to use JWT authentication for a REST API. I have the verifier running but I can’t get at the things I’d like to in the token, for example the scopes. If I look in the debugger I can see that the Payload is actually an Auth0 PayloadImpl. The Impl has a ‘tree’ property that has the data I need but this isn’t a public class so I can’t cast to it. Am I missing something, is there a way to get at the scopes for example?
    f
    z
    • 3
    • 6
  • s

    spierce7

    02/20/2019, 10:49 PM
    What is the best way to read the full response body of a Ktor
    HttpResponse
    as a String? We are finding crashes when we do things like
    response.content.readUTF8Line()
    z
    e
    • 3
    • 5
  • d

    davidasync

    02/21/2019, 5:09 AM
    Hello, just curious Why ktor http client cannot set header
    Content-type
    ?
    b
    • 2
    • 2
  • d

    davidasync

    02/21/2019, 3:04 PM
    Hello, I can set socketTimeout at different block, is there any differences between the block between
    engine block
    and
    customizeClient block
    ?
    val clientCall = HttpClient(Apache){
              engine {
                socketTimeout = config?.timeoutMsec ?: 10_000
                connectTimeout = config?.connectTimeout ?: 10_000
                connectionRequestTimeout = 20_000
    
                customizeClient {
                  setProxy(requestProxyHost)
    
                  socketTimeout = config?.timeoutMsec ?: 10_000
                  connectTimeout = config?.connectTimeout ?: 10_000
                  connectionRequestTimeout = 20_000
                }
              }
            }
    e
    • 2
    • 2
  • f

    fkrauthan

    02/21/2019, 8:36 PM
    My scenario is for my signature validation on my auth provider I need the "raw" string. And in my actual code I need it parsed as form parameters (using receiveParameters)
    c
    • 2
    • 2
  • d

    davidasync

    02/22/2019, 3:37 AM
    Hello I got this error, when do http call using ktor http client
    Request cannot be executed; I/O reactor status: STOPPED
    What does it mean ?
    e
    • 2
    • 1
  • r

    Riccardo Montagnin

    02/22/2019, 6:09 AM
    Hello everyone, I would like to implement a system in order to get push notifications for devices. What approach would you consider? I was thinking about authenticated websockets, but I'm not sure this would be the best approach. Have you guys any idea how I could implement such a feature with Ktor?
    m
    r
    • 3
    • 3
  • s

    Sergey Bondari

    02/22/2019, 6:22 AM
    I have a weird problem with HttpClient Logging feature, if I use body logging with call pipeline receive<InputStream> and then streaming the response into Jackson object mapper, the logger freezes at BODY START indefinitely. Is it a bug?
    r
    e
    • 3
    • 6
  • d

    davidasync

    02/22/2019, 8:23 AM
    Hello, with this code, why it hang up ? As you can see at console.log, it stop at the total cpu core
    suspend fun main () = coroutineScope {
        var counter = 1
        launch {
            while (true) {
                HttpClient(Apache) {
                    engine {
    
                    }
                }.use {
                    val clientResponse = it.call {
                        method = <http://HttpMethod.Post|HttpMethod.Post>
                        url(URL("<https://httpbin.org/post>"))
                        body = TextContent(bodyVal, contentType = ContentType("application", "json"))
                    }.response
    
                    val jsonResponseString = String(clientResponse.readBytes())
    
                    println(counter.toString())
                    counter += 1
                }
            }
        }
    
        println("abc")
    }
    e
    • 2
    • 9
  • l

    legzo

    02/22/2019, 9:50 AM
    Hi guys, I have some code that relies on MDC to log some context data (SessionID for example). I use Ktor Http Client to call some REST services, with OkHttp. I understand that the OkHttp calls are made using coroutines and I don't have access to MDC data that is based on
    ThreadLocal
    . I saw that
    kotlinx.coroutines.slf4j
    introduces
    MDCContext()
    and that, this way, you can launch some coroutines passing them MDC data. But is there a way I can use it to propagate my MDC data to the underlying OkHttp calls ?
    m
    s
    • 3
    • 4
  • d

    davidasync

    02/22/2019, 4:09 PM
    I have a service that do http call to other service. Is it okay to not close() the ktor http client ?
    s
    • 2
    • 1
  • d

    davidasync

    02/23/2019, 3:07 PM
    Hello, why this code block doesn't work ya ?
    fun exec () {
        GlobalScope.launch {
            var counter = 1
            val httpClient = HttpClient(Apache)
            while (true) {
                val clientResponse = httpClient.use {
                    it.call {
                        method = <http://HttpMethod.Post|HttpMethod.Post>
                        url(URL("<https://httpbin.org/post>"))
                        body = TextContent(bodyVal, contentType = ContentType("application", "json"))
                    }.response
                }
    
                val jsonResponseString = String(clientResponse.readBytes())
                println(counter.toString())
                counter += 1
            }
        }
    }
    
    suspend fun main () = coroutineScope {
        exec()
    
        Thread.sleep(1000000)
    }
    Is it because I use
    .use{
    ?
    s
    b
    • 3
    • 2
  • b

    bootstraponline

    02/23/2019, 4:56 PM
    with ktor I can do
    server.start(wait = false)
    however the server never stops.
    server.stop(1, 1, TimeUnit.SECONDS)
    server.application.dispose()
    result in the process staying alive, even though the netty worker pool is freed. Is there a way to fully stop the server and let the process naturally exit?
    • 1
    • 1
  • b

    bdawg.io

    02/23/2019, 11:13 PM
    What’s the
    ktor-auth
    idiomatic way to return a
    403 Forbidden
    for a found principal? I am able to authenticate the user with their credentials, but I committed to the clients that I would return a forbidden respond when the user is not authorized with a certain permission.
    r
    • 2
    • 1
  • d

    davidasync

    02/24/2019, 6:27 AM
    sorry noob question, I'm curious about how ktor implement http client call, is it will utilize coroutines for each http call instead of threads ?
    d
    • 2
    • 3
  • t

    tjb

    02/24/2019, 6:00 PM
    would anyone have any guidance if i wanted to send a param like
    ?myParam=text,2.0
    ?
    d
    r
    • 3
    • 4
  • s

    Sander Ploegsma

    02/25/2019, 7:59 AM
    Hi guys, can anyone help me figure out how to call two
    suspend
    functions in parallel inside a route? This compiles but crashes at runtime with `io.ktor.util.pipeline.SuspendFunctionGun cannot be cast to kotlinx.coroutines.CoroutineScope`:
    fun Routing.test() {
        get("/") {
            val firstResultDeferred = async { firstCall() }
            val secondResultDeferred = async { secondCall() }
            
            val firstResult = firstResultDeferred.await()
            val secondResult = secondResultDeferred.await()
    
            call.respond(listOf(firstResult, secondResult))
        }
    }
    g
    e
    c
    • 4
    • 19
  • s

    stanislav

    02/25/2019, 10:12 AM
    Hi guys, when using ktor's GMTDate, I'm getting this bug:
    // 10:18:47 4.FEB.2019
    // dateRaw: GMTDate = GMTDate(seconds=47, minutes=18, hours=10, dayOfWeek=MONDAY, dayOfMonth=4, dayOfYear=35, month=FEBRUARY, year=2019, timestamp=1549275527000)
    
    val date = dateRaw.toJvmDate()
    // date: Date (JVM/Android) — Mon Feb 25 13:07:27 GMT+03:00 2019 (CURRENT DATE)
    e
    • 2
    • 8
  • d

    dewildte

    02/25/2019, 4:34 PM
    to do otherwise you must add an annotation that tells Gson the expected JSON key for a field that does no match it.
    j
    • 2
    • 1
  • o

    obobo

    02/25/2019, 9:48 PM
    Hi, I have a question on how and why to use dispatchers. I have a ktor project in which I fetch a number of results from the database, then I need to split these results and send them to a separate service, waiting for the response. I've implemented this using Deferreds, and using awaitall() on them. My current implementation creates a
    CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>)
    and then uses
    async
    on it to create the Deferreds. My question is whether this is the correct way to do this, or if I should use the
    coroutineScope
    function to create the scope and call
    async
    from within. Unsure if this is a #ktor or #coroutines question, seems more like the former.
    b
    • 2
    • 2
  • p

    Patrick Jackson

    02/26/2019, 12:02 AM
    Anyone worked with deserializing a map? Guessing a custom serializer is needed.
    s
    • 2
    • 3
  • d

    Davide Giuseppe Farella

    02/26/2019, 2:26 AM
    I’m using Ktor for get a simple file. This unit test runs successfully 10/10
    fun `playlist realTest`() {
            val source = ParsersImpl()
    
            runBlocking {
                source.readFrom(
                        Playlist("<https://sourcetv.info/dl/01/it29.m3u>", SourceFile.Type.REMOTE ),
                        onChannel = { println( it ) },
                        onGroup = { println( it ) },
                        onError = { println( "${it.reason.name} - ${it.rawChannel}" ) }
                )
            }
        }
    The http call resides here:
    override suspend fun readBytes( path: String ) = client.get<ByteArray>( path )
    The problem is that when I run my Android app, 9/10 gives me the following exception
    ✔️ 1
    d
    • 2
    • 5
  • f

    fabian

    02/26/2019, 9:12 PM
    hi, does somebody mind pointing me at the right docs or method for how to access the original request (POST) body when a
    ContentConverter
    like the
    JacksonConverter
    is installed?
    s
    • 2
    • 2
Powered by Linen
Title
f

fabian

02/26/2019, 9:12 PM
hi, does somebody mind pointing me at the right docs or method for how to access the original request (POST) body when a
ContentConverter
like the
JacksonConverter
is installed?
s

Sergey Bondari

02/26/2019, 9:41 PM
in your route you can do something like
post("/foo") {
    call.receiveStream().use {
      // raw bytes from input body
    }
   // or
   call.receiveChannel() // will give you a ByteReadChannel primitive for the lowest level reading routine. 
}
there are many flavors of receive. When you have JSON transformer, you can do
call.receive<Foo>()
and it will attempt to deserialize payload into a
Foo
class instance
f

fabian

02/26/2019, 10:53 PM
thank you, I will mess around with that 🙂
View count: 1