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

    fbodr

    06/30/2022, 12:28 PM
    hi all. For those using kotlinx-serialization with ktor, how did you manage to use @Serializer custom serializers with content-negotiation plugin ? i have some classes that are auto generated (so I cannot annotate them with @Serializable), but I cannot find a way for ktor to use the custom serializer
    h
    a
    • 3
    • 5
  • r

    Raphael TEYSSANDIER

    06/30/2022, 5:42 PM
    Hello, I would to make a jar with shadowJar of Ktor + Vue.js. But Vue.js is not working with the jar. Any idea ?
    b
    • 2
    • 9
  • m

    Martin Gaens

    07/03/2022, 12:02 PM
    I'm building a Telegram Bot API library in Ktor and I realized there's something I don't understand about Ktor client. I'm using
    kotlinx.serialization
    for serializing objects and here's my issue: The Telegram API supports a lot of methods. Here's an example of one such method: The
    getFile
    method. It has one parameter:
    file_id
    which is of type
    String
    . These methods can receive their parameters through JSON objects. So, if I want to send a request to this method, I first create a
    class
    called
    GetFileJSONRequest
    with
    @SerialName()
    annotations (because in Kotlin, the parameter is called
    fileId
    and in JSON it has to be
    file_id
    ). And then, I send the request like this:
    val response: HttpResponse = <http://client.post|client.post>("<https://api.telegram.org/bot123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11/getFile|https://api.telegram.org/bot123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11/getFile>") {
        contentType(ContentType.Application.Json)
        setBody(GetFileJSONRequest(fileId = fileId))
    }
    This whole process with creating classes seems very tedious and I wonder if there's a much better solution to my problem.
    a
    a
    • 3
    • 14
  • f

    fbodr

    07/04/2022, 7:25 AM
    Hi all, good day. I would like to ask if someone know if its possible to run a ktor service with two different ports (and set of routes) so, for example, I can have the metrics scrapper running on a separate port) . I tried looking at the docs but could not figure out a way of doing that.
    s
    a
    • 3
    • 5
  • m

    Martin Gaens

    07/04/2022, 9:16 AM
    Could someone please help me with the
    kotlinx.serialization
    one? I saw on Stack Overflow that it's an unsolved mystery, but I feel like it is super important to know a good fix because it might be a deal breaker for some people.
  • j

    Jonas Trollvik

    07/04/2022, 11:49 AM
    Hi, Does anyone have a clue if it's possible to retrieve client principal when using the StatusPage plugin? The AuthContext does not seem to exist in call.attributes
    a
    • 2
    • 11
  • h

    hhariri

    07/05/2022, 9:28 AM
    📣 Ktor 2.0.3 has been released 📣 https://twitter.com/JetBrainsKtor/status/1543854529720061955
    👍 2
    :kotlin-intensifies: 1
    🎉 7
  • p

    Piotr Krzemiński

    07/05/2022, 11:49 AM
    here's a random and spontaneous THANK YOU for creating ktor 🙂 I know ktor a bit, and now learning about Spring Boot. I really like how ktor tackles routing and e.g. security - it's so clear to see which endpoints are secured with each mechanism, contrary to how it's done in Spring. No magic annotations! 🙂 Thanks and please keep up the great work!
    :tnx: 6
    ➕ 10
    🎉 2
  • p

    phldavies

    07/05/2022, 4:33 PM
    Should https://kotlinlang.org/docs/releases.html#release-details still reference ktor 2.0.0-beta1 as the recommend version?
    a
    • 2
    • 1
  • n

    Nick Halase

    07/05/2022, 5:41 PM
    Just hit my head on something that was totally my fault, but maybe could be improved on. I couldn't tell why I was getting 404s on my routes for some, but not all. I was using type-safe routing.
    import <http://io.ktor.server.resources.post|io.ktor.server.resources.post> // GOOD
    import <http://io.ktor.server.routing.post|io.ktor.server.routing.post> // BAD
    a
    • 2
    • 1
  • l

    Leonardo Borges

    07/06/2022, 6:44 AM
    I'm facing a weird error after migrating to ktor 2, about coroutine dispatcher limited parallelism. This is something they changed and added as support but seems weird that I need to set some configuration about it. Has someone experienced this issue? Using Ktor 2.0.3, Kotlin 1.7.0 and kotlinx-coroutines 1.6.0 (tried with 1.6.2 too)
    a
    • 2
    • 5
  • j

    jeggy

    07/06/2022, 12:05 PM
    In the ktor client docs https://ktor.io/docs/response.html#streaming. It shows usecase of a function called
    prepareGet
    but doesn't seem like this function exists
    • 1
    • 1
  • d

    Dirk

    07/06/2022, 3:31 PM
    After switching to Kotlin 1.7.0, my JS application with the Ktor client 2.0.2/2.0.3 throws an exception. Has anyone else observed this?
    a
    • 2
    • 6
  • s

    spierce7

    07/06/2022, 8:42 PM
    Is it possible to download a file from the local file system using ktor?
    b
    l
    +2
    • 5
    • 9
  • j

    Jonathan Mew

    07/08/2022, 9:42 AM
    We've started seeing an intermittent StacklessClosedChannelException since updating to ktor 2 (Netty). Is there anything we could try to squash them? Attaching stacktrace 🧵
    • 1
    • 1
  • c

    clayly

    07/09/2022, 8:49 PM
    Hi everyone! Trying to understand how to pass command-line options for array parameters (e. g.
    ktor.application.modules = []
    ), but it fails with error like this:
    Exception in thread "main" com.typesafe.config.ConfigException$WrongType: Command-line options: tasks has type STRING rather than LIST
    • 1
    • 6
  • m

    Martin Gaens

    07/11/2022, 12:34 AM
    I'm using a long polling method of retrieving data from the Telegram API and basically, the problem is that it takes sometimes too much time for the client to respond to a response. Basically, I send a request to the server, the server keeps the connection open until some new update arises, and when it does, the server (API) responds to my request, delivering new useful information. Now... It takes sometimes a second (which I consider too much time) from me sending a message until the client registers it. Here's the client code:
    private val client = HttpClient(CIO) {
        install(DefaultRequest)
        install(ContentNegotiation) {
            json(Config.json)
        }
        install(HttpTimeout) {
            connectTimeoutMillis = 30_000
            requestTimeoutMillis = 30_000
        }
        install(Logging) {
            level = LogLevel.ALL
        }
        defaultRequest {
            url("<https://api.telegram.org/bot${bot.token}/>")
        }
    }
    And this is how I handle the updates:
    internal val updateFlow: Flow<Update> = flow {
        while (true) {
            try {
                val updates = getUpdates(
                    offset = currentOffset,
                    timeout = KramBot.LONG_POLLING_TIMEOUT_SECONDS
                )
                // Telegram servers return an empty JSON array after the timeout if there are no updates
                if (updates.isEmpty()) continue
                updates.forEach { emit(it) }
                currentOffset = updates.last().updateId + 1
            } catch (e: HttpRequestTimeoutException) {
                println("Timed out.")
            }
        }
    }
    
    private suspend fun getUpdates(
        offset: Int? = null,
        limit: Int? = null,
        timeout: Int? = null,
        allowedUpdates: List<String>? = null
    ): List<Update> {
        val response = <http://client.post|client.post>("getUpdates") {
            with(url.parameters) {
                offset?.let { append("offset", it.toString()) }
                limit?.let { append("limit", it.toString()) }
                timeout?.let { append("timeout", it.toString()) }
                allowedUpdates?.let { append("allowed_updates", it.toString()) }
            }
        }
        when (val apiResponse = response.body<ApiResponse<List<UpdateDto>>>()) {
            is ApiResponse.Ok -> return apiResponse.result.map { it.toEntity() }
            is ApiResponse.Error -> error(
                """
                    Got an error response from the getUpdates method which should be impossible.
                    Error code: ${apiResponse.errorCode}
                    Description: ${apiResponse.description}
                """.trimIndent()
            )
        }
    }
    a
    • 2
    • 7
  • a

    albrechtroehm

    07/11/2022, 11:33 AM
    Hey everyone, I’m struggling with SSL and the ktor client. For some reason when i try to do a GET request with an HttpClient(CIO) i receive a
    Failed to parse HTTP response: unexpected EOF
    . After searching for a while I stumbled upon a java example where they were using this command:
    System.setProperty("jdk.tls.maxHandshakeMessageSize", "65536")
    . It did not change a thing when using HttpClient(CIO) but with HttpClient(Apache) the call is going through just fine now. Is there some other way to change the message size for CIO or should i just stick with the Apache engine?
    a
    • 2
    • 3
  • h

    Hamza GATTAL

    07/11/2022, 3:09 PM
    hi, everyone I'm using Ktor client 2.0.x with Bearer Auth. I have many requests don't need authorization. what is the way to tell Ktor don't add authorization header
    r
    • 2
    • 2
  • m

    Mikhail

    07/11/2022, 4:22 PM
    is there any way to catch connection errors in Ktor client? Am using OkHttp engine
    a
    • 2
    • 3
  • v

    Vinay Pothnis

    07/11/2022, 4:23 PM
    Hello Team! Whats the best way to get metrics from
    ktor-client
    ? It looks like the
    ktor-server
    has some metrics integrations - but I couldn’t quite get the details for the client.
    a
    • 2
    • 5
  • j

    Jonathan De Leon

    07/11/2022, 4:48 PM
    Is there a way to limit the file upload size using multipart with
    ktor-server
    ? I'm using
    1.6.8
    .
    a
    • 2
    • 2
  • l

    Louis Gautier

    07/11/2022, 6:59 PM
    Hello. I’m an Android developer who use Ktor in private and pro apps I’m learning the server side with Ktor and I’d like to expose a video file thought API (like real time streaming content). I know nothing about this kind of thing and I don’t even know where to begin with. Is Partial Content is the way ? Oh and is there any third party library that can help me to do so (+ can handle slow connection and stuff like this) ?
  • h

    hhariri

    07/13/2022, 11:38 AM
    📣 New Deployment Plugin 📣 We’ve just released a new plugin for Gradle that aims at simplifying deployment. It’s still in EAP, but we’d love to get some feedback. You can find instructions on how to use it on GitHub. https://github.com/ktorio/ktor-build-plugins
    👀 2
    b
    e
    +2
    • 5
    • 9
  • j

    Javier

    07/13/2022, 12:46 PM
    Is it possible to replace a mock response in an already created
    HttpClient
    without having to create other
    HttpClient
    ?
    a
    • 2
    • 2
  • s

    steamstreet

    07/13/2022, 6:34 PM
    I think I’ve discovered a bug with gzip client handling (and likely all compression plugins). If I issue a
    get
    for compressed data at a URL, and then call
    response.body<ByteArray>()
    the response bytes are truncated to the content length of the response, but that value is the compressed size. So it’s taking the uncompressed bytes, and truncated them to the size of the compressed data. Is there another way to get at the uncompressed data without doing the gzip stuff myself?
    a
    • 2
    • 5
  • h

    Hien Nguyen

    07/14/2022, 10:21 AM
    I need set NSURLSessionConfiguration into IosClientEngineConfig, how to do it ?
    t
    a
    • 3
    • 8
  • s

    Satyam Agarwal

    07/14/2022, 1:07 PM
    Hei Hei. I am wondering if Ktor team has concluded something regarding open api doc generation/ swagger support so far ? Would be super interesting to hear if you have thought about how this will be supported in the framework or the project attached in the swagger youtrack ticket will be adopted as is ? It was mentioned in the roadmap https://blog.jetbrains.com/ktor/2022/02/11/ktor-roadmap-what-s-next/
    👀 1
    s
    t
    a
    • 4
    • 9
  • c

    CLOVIS

    07/14/2022, 3:21 PM
    Is there a way to have a route with optional authentication? I have a specific route that both users and anonymous clients can access.
    e
    • 2
    • 5
  • l

    Lawrence

    07/14/2022, 8:31 PM
    What would be the equivalent of this curl statement in ktor?
    curl -X POST \
        $url \
        -H "Accept: application/json" \
        -H "Content-Type: application/octet-stream" \
        --data-binary "@$FILE"
    i tried sending the file as body but I quickly ran out of memory with
    setBody(file.readBytes()
    . Is there a streaming implementation without using MultiPartForm?
    e
    a
    • 3
    • 2
Powered by Linen
Title
l

Lawrence

07/14/2022, 8:31 PM
What would be the equivalent of this curl statement in ktor?
curl -X POST \
    $url \
    -H "Accept: application/json" \
    -H "Content-Type: application/octet-stream" \
    --data-binary "@$FILE"
i tried sending the file as body but I quickly ran out of memory with
setBody(file.readBytes()
. Is there a streaming implementation without using MultiPartForm?
e

ephemient

07/14/2022, 8:36 PM
https://api.ktor.io/ktor-http/io.ktor.http.content/-u-r-i-file-content/index.html
👀 1
a

Aleksei Tirman [JB]

07/15/2022, 4:26 AM
val client = HttpClient(Apache)

val response = <http://client.post|client.post>(url) {
    header(HttpHeaders.Accept, ContentType.Application.Json)
    contentType(ContentType.Application.OctetStream)
    setBody(FILE.readChannel())
}
👀 1
View count: 5