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

    Hitesh Chopra

    09/02/2021, 2:43 PM
    Hi, I am new to Ktor. How can access secret values from application.conf in Ktor outside any Application extension function? I am trying to fetch values as environment.config.property("key").toString() in a seperate object outside the application module but it does not work. How to fix that? Thanks in advance
    l
    • 2
    • 3
  • l

    landon burch

    09/03/2021, 4:43 PM
    I am running into io.ktor.client.call.NoTransformationFoundException: No transformation found: I checked the returning JSON and my object has the same fields .. any ideas on what I should try?
    a
    • 2
    • 1
  • h

    Hitesh Chopra

    09/04/2021, 7:28 AM
    Hi, is there any way I can debug or set breakpoints for incoming APIs requests in Ktor? The logs are returning minimal information. Actually I have implemented JWT authentication in ktor and I am getting status code 401(unauthorised) in API response and something similar in logs as well. I am stuck here since long time, how do I get more details on what is causing it?
    h
    c
    a
    • 4
    • 8
  • v

    Vasily Scherbakov

    09/04/2021, 9:06 AM
    Hi, everyone! Recently, i started to develop web app using vaadin framework. My aim is to fetch data from REST API. I tried use ktor client for this, but i have the next problem: i need to invoke suspend function in non suspend context(variable declaration). This is my view code:
    class MainView : KComposite() {
        private val apiClient: ScenarioServiceClient = ScenarioServiceClientImpl("<http://localhost:5000>");
        private val root = ui {
            verticalLayout {
                horizontalLayout {
                div{
                    addClassName("centered-content")
                     apiClient.getAvailableScenarios()
                        .forEach { scenario -> scenarioItemView(scenario) }
                }
            }
        }
    }
    This is how i use ktor:
    class ScenarioServiceClientImpl(private val baseUrl: String) : ScenarioServiceClient {
        private val restClient: HttpClient = HttpClient(Apache)
        override suspend fun getAvailableScenarios() : List<ScenarioViewModel>{
            val scenarios = restClient.get<List<ScenarioViewModel>>("${baseUrl}/scenarios")}}
    May be there is some way to invoke api call without suspend?
    d
    a
    • 3
    • 3
  • e

    Evgeny Berezovsky

    09/05/2021, 10:22 PM
    Hello, everyone I am using the ktor 1.6.3 client and serialization to send requests Before that, everything worked correctly, but now I need to send an image to the chat of the application that I am doing For client settings,
    defaultRequest
    uses
    header(HttpHeaders.ContentType, ContentType.Application.Json)
    When sending via
    submitFormWithBinaryData
    , it returns the error
    kotlinx. serialization. SerializationException: Serializer for class 'MultipartFormDataContent' is not found
    I tried to change
    header
    for the request to send an image with
    contentType
    , but I get another error
    io.ktor. http.UnsafeHeaderException: Header(s) [Content-Type] are controlled by the engine and cannot be set explicitly
    Judging by https://youtrack.jetbrains.com/issue/KTOR-620, I can't do this Setting
    contentType
    for
    MultipartFormDataContent
    does not give anything How can I send a request with a serializable class of type
    AddImageToMessage (val messageId: Int)
    and attach an image to this request?
    e
    a
    • 3
    • 11
  • d

    Didier Villevalois

    09/06/2021, 3:34 PM
    [ktor-network] @e5l Hi, I am starting to think about the implementation for the support of unix domain sockets (aka ipc sockets) in ktor-network as I proposed before. After delving in the code, I already have a few questions: 1. Should I first open a ticket on YouTrack before submitting a PR? 2. It seems that I would not have a lot to do for the native part (did not look at the Jvm part yet) because the posix API is the same to use IPC sockets modulo some constants (mainly the address family,
    AF_UNIX
    instead of
    AF_INET
    ). However, I think I would need to do some (problematic?) refactoring first. ◦
    AConnectedSocket
    and
    ABoundSocket
    both use
    NetworkAddress
    for their
    remoteAddress
    and
    localAddress
    which is problematic, because too restrictive. Presumably, I would have to introduce some super-class to
    NetworkAddress
    and another sibling to
    NetworkAddress
    (say
    UnixAddress
    ). This refactoring could ripple a lot. ◦ Rename
    TCPSocketNative
    to
    ByteStreamSocketNative
    as its implementation would be used as is for both TCP byte-stream sockets and IPC byte-stream sockets. (Same for
    TCPServerSocketNative
    ) ◦ Adapt the first two lines of both
    connect()
    and
    bind()
    (in
    ConnectUtilsNative.kt
    ) to also handle the
    UnixAddress
    . The rest of the code would (more or less) stay as is. That's all for now. I am quite ready to jump on the wagon, as there won't be much work to do (and I desperately need this 🤪). Please guide me on how I should proceed. Thanks in advance.
    e
    • 2
    • 4
  • p

    Paul Woitaschek

    09/06/2021, 8:12 PM
    We are using the ktor
    URLBuilder
    to create urls in a type safe way. However suddenly lots of warnings popped up that the whole parameters api is marked as internal. (ParametersBuilder is public) but functions like
    append
    belong to
    StringValuesBuilder
    and are marked as
    InternalAPI
    . Is there really no public api to create an url with parameters?
    ☝️🏾 1
    ☝️🏼 2
    e
    h
    a
    • 4
    • 3
  • d

    darkmoon_uk

    09/07/2021, 4:18 AM
    message has been deleted
    👍 2
    d
    a
    • 3
    • 3
  • b

    Barry Fawthrop

    09/07/2021, 7:37 PM
    Using android studio, how do you run and start a ktor project, with live updates? Thanks
    a
    • 2
    • 3
  • v

    Viktor Petrovski

    09/08/2021, 8:16 AM
    When using Ktor client for consuimg REST API as far as I understand
    val status = HttpClient().use { client ->
        // ...
    }
    should be preferred to
    client.get("<https://ktor.io/>")
    So there is no need to call the
    .close()
    function
    :yes: 1
    a
    b
    • 3
    • 9
  • b

    Barry Fawthrop

    09/08/2021, 10:34 PM
    Anyone know of an example/tutorial for a ktor rest server that uses productflavors so you can have different configuration variables for QA and production environments. Thanks
    ł
    a
    • 3
    • 10
  • p

    Piotr Krzemiński

    09/09/2021, 8:56 AM
    Hi ktor Team, I'm wondering if there's a chance to get some traction for Intergate Swagger UI Hosting as Ktor Feature : KTOR-774. OpenAPI/Swagger is de facto standard when it comes to such API documentation. Looking at the comments and reactions under them, there's been pretty massive interest. Barely half-solutions exist as separate libraries. The lack of this feature is a show-stopper in introducing ktor in my company. On behalf of the community, could we get some update from your side regarding plans for this feature? It could really boost adoption of ktor.
    👍 2
    a
    s
    r
    • 4
    • 3
  • j

    Jeff

    09/09/2021, 9:04 AM
    Keep getting this error recently. But my server is up and running 🤷🏾 What's up?
    REQUEST https://....... failed with exception: io.ktor.client.features.HttpRequestTimeoutException: Request timeout has been expired [url=https://......., request_timeout=15000 ms]
    p
    • 2
    • 13
  • t

    Trevor Stone

    09/09/2021, 5:05 PM
    Unimportant question, where did the name Ktor come from?
    ➕ 3
    m
    d
    a
    • 4
    • 4
  • j

    Jan

    09/10/2021, 10:56 AM
    I get an error when trying to post to some website, but I don't really understand that error because it doesn't really give me much information. Error: (see thread)
    a
    • 2
    • 6
  • b

    Bart

    09/11/2021, 2:42 PM
    Hello All, Im trying to learn how to create ktor server. I tried to configure self-signed SSL. But it ends with confussion. I have main fun looks like this:
    Fun main(arqs: Array<String>): Unity = io.ktor.server.jetty.EngineMain.main(arqs)
    If I understand correctly i need to create certificate before server in fun main. So its should goes like this:
    fun main(arts: Array<String>{
    <My certificate code>
    Unity = io.ktor.server.jetty.EngineMain.main(arqs)
    }
    As it cant be done like this, how it can be configured? Examples that i find are created for embeddedServer so i can't use it.
    a
    • 2
    • 2
  • d

    Didier Villevalois

    09/11/2021, 4:59 PM
    Does Ktor still support Java 1.6?
    d
    e
    • 3
    • 7
  • i

    IsaacMart

    09/13/2021, 3:40 AM
    Hello all, I have a model in my android project that has a type converter of a custom class. My android project has a backend built on ktor. The kto project also has a similar model and am using postress database for storage. The problem that i am facing is storing the type converted class inside my postgress alongside other attributes. Here is the models of the two. Thanks in advance. Android model
    @Entity(tableName = "requests")
    public class Request extends BaseObservable implements Parcelable {
        @PrimaryKey(autoGenerate = true)
        private int request_id;// Document_id
    
        private String r_clients_id;
        private int r_tasker_id;
        private User user;// Type converter 
        private String requested_skill;
        private String time_stamp;
    }
    Same model for my ktor project
    class Request(
        val request_id: Int,
    
        val r_clients_id: Int,
        val r_tasker_id: Int,
        val user: User,
        val requested_skill: String,
        val time_stamp: String,
        val arrival_date: String,
    ): Serializable, Principal
    Here is where am facing the challenge. I really don't know how to insert or reference the Type converter class in my object class.
    object Requests : Table() {
        val requestId: Column<Int> = integer("request_id").autoIncrement().primaryKey()
        val rClientId: Column<Int> = integer("r_clients_id").references(Users.userId)
        val rTaskerId: Column<Int> = integer("r_tasker_id").references(Taskers.taskerId)
        val user: Column<User> = ?????????????????????????
    
        val requestedSkill = varchar("requested_skill", 128)
        val timeStamp = varchar("time_stamp", 64)
        val arrivalDate = varchar("arrival_date", 64)
    }
    a
    • 2
    • 2
  • a

    Arnab

    09/13/2021, 7:04 AM
    Hey all! Say I have a
    graphql
    route in my ktor app. I want that route to be authenticated, but I don't want there to be any authentication on
    Introspection
    queries. Is that possible?
    a
    n
    • 3
    • 7
  • n

    natario1

    09/13/2021, 2:10 PM
    How do you reset the auth tokens previously passed to
    install(Auth) { bearer { ... } }
    ? We're having serious issues after logout/re-login, because apparently ktor keeps the old token in memory (loadTokens / refreshTokens not called). Using ktor client 1.6.0.
    r
    • 2
    • 4
  • j

    Jose A.

    09/14/2021, 11:59 AM
    I need to save the request body to a file. Something like this:
    post {
       val targetChannel = FileOutputStream(Files.createTempFile("job-", ".json").toFile()).channel
       val originChannel = newChannel(call.receiveStream())
    
       originChannel.use {
           targetChannel.use {
                targetChannel.transferFrom(originChannel, 0L, 100000)
           }
        }
    ...
    FileOutputStream, etc. are blocking calls. Is there a nonblocking API to write to files so I can use
    receiveChannel()
    ?
    a
    • 2
    • 4
  • j

    Jeff Lockhart

    09/15/2021, 6:50 PM
    I'm getting the warning "This API is internal in ktor and should not be used. It could be removed or changed without notice." using the
    append()
    or
    appendAll()
    functions to add headers to a request. For example, the example in the documentation:
    val response: HttpResponse = client.get("<https://ktor.io/>") {
        headers {
            append(HttpHeaders.Accept, "text/html") // warning
            append(HttpHeaders.Authorization, "token") // warning
            append(HttpHeaders.UserAgent, "ktor client") // warning
        }
    }
    Is there a new pattern that should be used for this? Why is
    StringValuesBuilder
    marked
    @InternalAPI
    now? Using ktor 1.6.3.
    r
    • 2
    • 2
  • s

    subashz

    09/15/2021, 6:51 PM
    can we execute notification service after we respond the data
    get("/test") {
        call.respond("hello")
        sendNotification() // does this function call execute properly
    }
    v
    a
    • 3
    • 3
  • d

    Danish Ansari

    09/16/2021, 6:40 AM
    If I have to deploy Ktor Rest APIs using SQLite DB, so I need JRE or Server JRE to be installed on my server? And which version of JRE?
    a
    • 2
    • 10
  • p

    Peter Mandeljc

    09/16/2021, 9:56 AM
    I'm looking at token auth docs and I'm confused what to do, if API does not return refresh token. BearerTokens seems to enforce refresh token. Any pointers?
    a
    • 2
    • 1
  • o

    Osmium

    09/16/2021, 10:00 AM
    Have anyone experienced issues with intercepting Authentication phases? I described situation in YouTrack, but maybe the solution is obvious... https://youtrack.jetbrains.com/issue/KTOR-3156
    a
    • 2
    • 1
  • i

    IsaacMart

    09/17/2021, 3:52 AM
    Hello guys. I have an issue with coroutine and am requesting for a fix in this. My rowToRequest method is a suspend function and throws an error of "Suspension functions can be called only within coroutine body."
    override suspend fun getAllRequestsById(user_id: Int): List<Request> {
            return DatabaseFactory.dbQuery {
                Requests.select { Requests.rClientId.eq(user_id) or Requests.rTaskerId.eq(user_id) }.mapNotNull { rowToRequest(it) } //  Suspension functions can be called only within coroutine body
            }
    
        }
    Here is my rowToRequest() function
    private suspend fun rowToRequest(row: ResultRow?): Request? {
            if (row == null) {
                return null
            }
            return userRepository.getUser(row[Requests.user])?.let {user ->
                taskerRepository.getTasker(row[Requests.tasker])?.let { tasker ->
                    Request(
                        row[Requests.requestId],
                        row[Requests.rClientId],
                        row[Requests.rTaskerId],
                        user,
                        tasker,
                        row[Requests.requestedSkill],
                        row[Requests.timeStamp],
                        row[Requests.arrivalDate],
                        row[Requests.arrivalTime],
                        row[Requests.taskDescription],
                        row[Requests.task1ImgUrl],
                        row[Requests.task2ImgUrl],
                        row[Requests.task3ImgUrl],
                        row[Requests.task4ImgUrl],
                        row[Requests.notificationStatus],
                        row[Requests.viewHolderNotificationType],
                        row[Requests.receiptNo],
                        row[Requests.taskStatus],
                        row[Requests.isNotificationSeen],
                        row[Requests.dateOfAcceptance],
                        row[Requests.dateOfDecline],
                        row[Requests.dateOfExpire],
                        row[Requests.convenienceFee],
                        row[Requests.paymentDate],
                        row[Requests.paidAmount],
                        row[Requests.paymentOption],
                        row[Requests.paymentStatus],
                        row[Requests.clientRatingStar],
                        row[Requests.clientRatingFeedback],
                        row[Requests.feedbackDate],
                    )
                }
            }
        }
    a
    • 2
    • 2
  • b

    benkuly

    09/17/2021, 10:58 AM
    I want to upload a byte stream with ktor-client. The body is set to a
    ByteReadChannel
    , but then the
    Content-Length
    -header is not set. Setting it manually throws:
    Header(s) [Content-Length] are controlled by the engine and cannot be set explicitly
    io.ktor.http.UnsafeHeaderException: Header(s) [Content-Length] are controlled by the engine and cannot be set explicitly
    a
    • 2
    • 2
  • c

    Cristian Rosa

    09/19/2021, 12:34 PM
    Hi all, I would like to run a small server in ktor, and I need a simple GUI to perform some customization on it. (I thought would be a good chance to get into jetbrains compose 😁*)* I can’t figure out you to stop and re-start server either with “embedded” nor “Engine version on ktor At the moment relevant code looks like
    @Composable
    fun MainScreen() {
    
        val ktorServer = embeddedServer(Jetty, port = 8080,) {
           
        ...module declaration....
     
        }
    
        Column(Modifier.fillMaxSize(), Arrangement.spacedBy(5.dp)) {
            Button(modifier = Modifier.align(Alignment.CenterHorizontally),
                onClick = {
                    ktorServer.start(wait = false)
                }
            ) {
                Text("START")
            }
            Button(modifier = Modifier.align(Alignment.CenterHorizontally),
                onClick = {
                    ktorServer.stop(5000, 6000, TimeUnit.MILLISECONDS)
                }
            ) {
                Text("STOP")
            }
        }
    }
    At the moment • “start” button click works as expected and the server run properly • “stop” doesn’t take any action at all!!!! The only way, I figure out to stop the server is by shutdown-url, but in this way the all app is closed (I would like to keep the compose windows open with the change of re-start server again) Using EngineMain like this:
    scope.launch(Dispatchers.Default) {
       val args = arrayOf<String>()
       EngineMain.main(args)
    }
    Again I can run the server but don’t know how to stop it.
    a
    • 2
    • 6
  • b

    Big Chungus

    09/19/2021, 2:17 PM
    I've raised a PR for CBOR support on the client and would appreciate some feedback.
    h
    • 2
    • 4
Powered by Linen
Title
b

Big Chungus

09/19/2021, 2:17 PM
I've raised a PR for CBOR support on the client and would appreciate some feedback.
h

hfhbd

09/19/2021, 2:18 PM
You should create an issue in Youtrack too
b

Big Chungus

09/19/2021, 2:19 PM
Wasn't aware of this, will do. Thanks!
👍 1
h

hfhbd

09/20/2021, 9:40 AM
BTW breaking changes are allowed in brach
2.0.0-eap
b

Big Chungus

09/20/2021, 11:11 AM
https://youtrack.jetbrains.com/issue/KTOR-3174
View count: 1