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

    jk2018

    02/24/2020, 10:32 PM
    It's not well documented at all, but you do need to have curl installed ( how depends on the platform.). Some instructions are here: https://github.com/JetBrains/kotlin-native/tree/master/samples/libcurl
    e
    • 2
    • 7
  • n

    Nikky

    02/25/2020, 8:23 AM
    https://ktor.io/servers/features/locations.html#parameters-get here it mentions that additional parameters are retrieved from get or post parameters.. i guess that means that i can use forms with post action? is there any specific encoding type i have to use for this ? i tried this and it always says that the post request is unhandled
    s
    c
    • 3
    • 5
  • n

    Nikky

    02/25/2020, 8:56 AM
    is there any utilities for receiving a post body (FormEncode.multipartFormData from a form) into a data class or something @Serializable other than
    call.receiveMultipart()
    and manually receiving all parameters ?
    c
    • 2
    • 1
  • w

    waltermcq

    02/25/2020, 9:12 PM
    Hello, noob question for ktor and json via GSON (edit: solved)
    a
    • 2
    • 18
  • n

    Niro

    02/26/2020, 3:00 PM
    private val client by lazy {
            HttpClient(engine) {
                install(JsonFeature) {
                    serializer = KotlinxSerializer(Json.nonstrict).apply {
                        setMapper(Todo::class, Todo.serializer())
                    }
                }
                install(WebSockets)
            }
        }
    
        suspend fun fetchNotes(): List<Todo> {
            val jsonString2 = client.get<String> {
                url("$baseUrl/todos")
                
            }
            return Json.nonstrict.parse(multiNoteSerializer, jsonString2)
        }
    c
    • 2
    • 6
  • j

    Jeff

    02/27/2020, 12:03 PM
    Hi guys whenever I update Ktor to version 1.3.1 from 1.1.2 in multiplatform it can no longer resolve KotlinxSerializer() What am I doing wrong?
    e
    • 2
    • 3
  • s

    Saood

    02/27/2020, 4:21 PM
    Did anyone tried configureSession() with ktor to set delegate for certificate validation? ktor version 1.3
    Ios.create {
        configureSession {
        }
    }
    Delegate method for certificate validation
    func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void)
    e
    t
    a
    • 4
    • 17
  • n

    Narek Mailian

    02/28/2020, 11:29 AM
    Hi! I'm trying to serialize a list of polymorphic objects, but get the error "Serializing collections of different element types is not yet supported". Is there any workaround one can use? (besides wrapping everything in a serializable data class with a list)
    t
    l
    • 3
    • 4
  • j

    Jan Stoltman

    02/28/2020, 12:55 PM
    Hey, is there any way to catch exceptions thrown by Ios client engine when there is no internet connection? So far I cannot wrap my head around how swift errors are propagated into kotlin
    j
    • 2
    • 1
  • c

    codec

    02/28/2020, 7:41 PM
    log()
    function… because it’s not in the
    org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3
    library…
    r
    j
    • 3
    • 5
  • m

    Muh Rahmatullah

    02/29/2020, 6:47 PM
    Hi all, new to ktor, I am creating simple api using ktor and gson for json serialization. I tried to handle simple POST request which has json payload but I always got error when I wanted to retrieve the payload using
    call.receive<Foo>()
    and the error is
    java.lang.UnsupportedOperationException: This function has a reified type parameter and thus can only be inlined at compilation time, not called directly.
    this is the post handler:
    fun Route.createMovie(movies: MutableList<Movie>) {
        post("/movie") {
            val id = Random.nextInt(1, 100000)
            println("header ${call.request.headers["Content-Type"]}")
            if(movies.find { it.id == id.toString() } != null) {
                // this is example to modify status code in the response and assign the value to the response wrapper
                call.response.status(value = HttpStatusCode.BadRequest)
                call.respond(Response(data = null, code = call.response.status()?.value, message = "Movie with $id already exist"))
            } else {
                val payload = call.receive<Movie>()
                println(payload)
                movies.add(payload)
                call.respond(Response(data = movies, code = 200, message = "OK"))
            }
        }
    }
    and my Application
    fun Application.module(testing: Boolean = false) {
    
        val movies = initData()
    
        install(ContentNegotiation) {
            gson {
                setPrettyPrinting()
            }
        }
    
        routing {
            get("/") {
                call.respondText("A very simple rest api using k-tor!", contentType = ContentType.Text.Plain)
            }
            movies(movies)
            movieById(movies)
            deleteById(movies)
            createMovie(movies)
        }
    }
    Also, I already set the Content-type to application/json when sending the request. TIA, any help would be great
    • 1
    • 1
  • r

    ribesg

    03/01/2020, 12:42 PM
    When using the Ktor Client in JS, getting an URL like
    /example
    gets
    <http://localhost/example>
    . Is it intended?
    🇳🇴 1
    e
    • 2
    • 4
  • s

    sultanofcardio

    03/02/2020, 7:16 PM
    Hi everyone. I'm interested in generating swagger docs and serving swagger UI from ktor. The serving part is pretty easy with static files but there seems to be no official way to generate swagger docs from ktor routes. There is also this (https://github.com/ktorio/ktor/issues/453) unofficial solution which hasn't gotten any attention from JB since its reporting in 2018. Can anyone say if this is a feature JB is looking at?
    c
    • 2
    • 3
  • s

    Shan

    03/02/2020, 11:00 PM
    Hey all. I have my
    AndroidEngineConfig
    set up in a way that if the method isn't
    GET
    ,
    HEAD
    or
    DELETE
    to set the content type to
    ContentType.Application.Json
    . This is fine for all of my
    POST
    requests with bodies, but I now need to make a
    POST
    request without a body (it is only a path with an Empty response), and I am getting:
    io.ktor.http.UnsafeHeaderException: Header Content-Type is controlled by the engine and cannot be set explicitly
    Is there any way I can override the
    Content-Type
    for this single request, or is there a way I can programmatically set it for each individual request?
    r
    e
    • 3
    • 4
  • h

    Henrik

    03/03/2020, 11:07 AM
    Hello all. I am using ktor in Android+iOS, but I have a problem with ktor not downloading the entire file always. When downloading to ByteArray, the array does not contain all the bytes of the file. Any ideas why? Is this call not blocking, so I read it prematurely or similar? Using ktor 1.3.1 and Kotlin 1.3.61
    private val client = HttpClient()
    val result: ByteArray = client.get {
                            url(url.toString())
                        }
    m
    e
    • 3
    • 17
  • s

    sultanofcardio

    03/03/2020, 5:48 PM
    I think version
    1.3.70-release-IJ2019.3-1
    of the Kotlin plugin in IntelliJ has broken ktor builds. The source of this stack trace is the declaration of the
    Application.module
    extension function
    stacktrace.txt
    d
    d
    e
    • 4
    • 5
  • r

    ribesg

    03/04/2020, 9:45 AM
    If anyone has an idea on how I could help fix this issue https://github.com/ktorio/ktor/issues/1650 I already spent some hours trying to create a reproducer with no luck
    ❗ 1
    m
    • 2
    • 2
  • t

    tylerwilson

    03/04/2020, 6:12 PM
    Do we need an updated ktor to work with kotlin 1.3.70 and serialization 0.20.? I am getting the following error at run time:
    java.lang.NoSuchFieldError: No field Companion of type Lkotlinx/serialization/json/Json$Companion; in class Lkotlinx/serialization/json/Json; or its superclasses (declaration of 'kotlinx.serialization.json.Json' appears in /data/app/com.webappclouds.salonbiz-ZLc1BlPrwYueYBzBSLTUTg==/base.apk!classes3.dex)
    :yes: 1
    g
    r
    • 3
    • 3
  • j

    John Peña

    03/04/2020, 9:51 PM
    is there a way to make a
    TestApplicationCall
    without going through all the tediousness of making a test server, test engine, test request, etc
    c
    • 2
    • 1
  • n

    napperley

    03/04/2020, 10:55 PM
    Appears as though Ktor Client hasn't caught up to support Kotlin 1.3.70 yet. Waiting for a newer version of the io.ktor:ktor-client-curl artifact with support for the linuxX64 target.
    • 1
    • 1
  • n

    napperley

    03/05/2020, 1:35 AM
    Is there a early access version of Ktor Client available that supports Kotlin 1.3.70?
    r
    • 2
    • 1
  • n

    napperley

    03/05/2020, 1:41 AM
    Is this version of Ktor Client ( https://mvnrepository.com/artifact/io.ktor/ktor-client/1.3.0-rc3-1.3.70-eap-42 ) related to Kotlin 1.3.70?
    r
    • 2
    • 1
  • r

    rrva

    03/05/2020, 10:36 AM
    Using ktor client, how do I handle a JSON response of type List<Foo> ? I get kotlinx.serialization.SerializationException: Can't locate argument-less serializer for class kotlin.collections.List. For generic classes, such as lists, please provide serializer explicitly. How do I provide a specific list serializer? I am on ktor 1.2.x but can upgrade to 1.3.1
    e
    • 2
    • 4
  • g

    gabin

    03/05/2020, 2:42 PM
    Hi guys, I’m using ktor+kotlinx.serialization. When I’m trying to get typed response I get a runtime crash:
    Exception in thread "main" java.lang.NoClassDefFoundError: kotlinx/serialization/ShorthandsKt
    at io.ktor.client.features.json.serializer.KotlinxSerializerKt.buildSerializer(KotlinxSerializer.kt:91)
    at io.ktor.client.features.json.serializer.KotlinxSerializerKt.access$buildSerializer(KotlinxSerializer.kt:1)
    at io.ktor.client.features.json.serializer.KotlinxSerializer.write(KotlinxSerializer.kt:69)
    at io.ktor.client.features.json.JsonFeature$Feature$install$1.invokeSuspend(JsonFeature.kt:101)
    at io.ktor.client.features.json.JsonFeature$Feature$install$1.invoke(JsonFeature.kt)
    at io.ktor.util.pipeline.SuspendFunctionGun.loop(PipelineContext.kt:273)
    Can you point me what’s wrong? ktor 1.3.1, serialization 0.20.0
    s
    • 2
    • 3
  • g

    gabin

    03/05/2020, 4:56 PM
    I’ve installed logging feature, but it seems not working
    install(Logging) {
        logger = Logger.ANDROID
        level = LogLevel.ALL
    }
    implementation "io.ktor:ktor-client-logging-jvm:$ktorVersion"
    in logs I only see exception:
    2020-03-05 16:16:33.829 1383-1383/? W/System.err: SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
    2020-03-05 16:16:33.829 1383-1383/? W/System.err: SLF4J: Defaulting to no-operation (NOP) logger implementation
    2020-03-05 16:16:33.829 1383-1383/? W/System.err: SLF4J: See <http://www.slf4j.org/codes.html#StaticLoggerBinder> for further details.
    is there a way to make it work ?
    r
    c
    • 3
    • 4
  • c

    christophsturm

    03/06/2020, 10:56 AM
    does ktor have an oauth2 client?
    c
    s
    • 3
    • 3
  • c

    CLOVIS

    03/06/2020, 11:21 AM
    Hi! I'm new at Ktor and kotlinx.serialization so this may be a very dumb question, sorry if that's the case... I'm trying to setup a multiplatform client to access some REST API. My example is an endpoint (
    /account/auth/
    ) which I should send a JSON object to, which contains a field
    username
    and a field
    password
    . It should return a JSON object that contains a
    token
    field. I want to use Kotlinx.Serialization to generate the JSON objects, so I started with:
    @Serializable
    private data class ApiUsernamePassword(val username: String, val password: String)
    and I do my request like this:
    val client = HttpClient() {
        install(JsonFeature) {
            serializer = KotlinxSerializer()
        }
    }
    
    val res = <http://client.post|client.post><String> {
        url("<http://localhost:8000/account/auth/>")
    
        body = ApiUsernamePassword(username, password)
    }
    On the JVM, I get this error:
    Companion
    java.lang.NoSuchFieldError: Companion
    	at io.ktor.client.features.json.serializer.KotlinxSerializer.<init>(KotlinxSerializer.kt:22)
    (I can send the full stacktrace if needed) On JS, I get this error:
    TypeError: Cannot read property 'plain' of undefined
    
        at new KotlinxSerializer (<http://localhost:9876/absolute/[REDACTED]/adapter-browser.js?fb6a5f1e12e8cc2bf794189b2b55f22def38ca94:157371:29>)
    I've tried Googling it but I don't get any meaningul/related results for both of those errors... Did anyone encounter this before? I also tried adding an empty companion object to my serializable class but it didn't change anything. (all of the above is in the common module, if that's relevant)
    g
    r
    • 3
    • 8
  • g

    gabin

    03/06/2020, 12:02 PM
    hey guys, is there some mechanism that allows to make refresh token request if I got a special error and repeat the initial request after that ?
    r
    • 2
    • 8
  • t

    tim

    03/07/2020, 3:42 PM
    Hi folks, i'm struggling to figure out how to test a ktor client making a post request. I have a class called MailSender which posts to a remote server. In MailSenderTest I would like to catch the underlying post request inspect it ... but I can't seem to figure out how to do this. I was looking into the MockEngine, but to get that to work MailSender needs to have access to the MockEngine which is in my testImplementation dependencies ... this should be straightforward so i'm clearly missing something ... any suggestions?
    r
    • 2
    • 2
  • j

    jpg

    03/08/2020, 10:41 AM
    If you are not tied to Apache Kafka I would consider using something different for this usecase. Depending on your requirements an AMQP based system could work or Apache Pulsar which has better messaging like semantics that are more suited to this workload than Kafkas streaming worldview.
    s
    • 2
    • 1
Powered by Linen
Title
j

jpg

03/08/2020, 10:41 AM
If you are not tied to Apache Kafka I would consider using something different for this usecase. Depending on your requirements an AMQP based system could work or Apache Pulsar which has better messaging like semantics that are more suited to this workload than Kafkas streaming worldview.
s

Shizo

03/08/2020, 10:48 AM
Thanks. I will check it out
View count: 3