I configure my Ktor `HttpClient` so that I can inj...
# ktor
o
I configure my Ktor
HttpClient
so that I can inject the root URL from DI and just consume
HttpClient
elsewhere without knowing about it, using only "path" in requests. When using a prod URL it works, when using localhost:8080 it fails. If I remove this mechanism and inline
<http://localhost:8080>
before all "path" it works too. So, I can't figure out where the issue resides 😞 🧵
Copy code
defaultRequest {
                if (url.host.isEmpty()) {
                    val defaultUrl = URLBuilder().takeFrom("<http://localhost:8080>")
                    url.host = defaultUrl.host
                    url.port = defaultUrl.port
                    url.protocol = defaultUrl.protocol
                    if (!url.encodedPath.startsWith('/')) {
                        val basePath = defaultUrl.encodedPath
                        url.encodedPath = "$basePath/${url.encodedPath}"
                    }
                }
            }
Copy code
httpClient.post("some/endpoint")
Copy code
httpClient.post("/some/endpoint")
vs
Copy code
httpClient.post("<http://localhost:8080/some/endpoint>")
I get a
ConnectException
Copy code
java.net.ConnectException: Connection refused
	at java.base/sun.nio.ch.Net.pollConnect(Native Method)
	at java.base/sun.nio.ch.Net.pollConnectNow(Unknown Source)
	at java.base/sun.nio.ch.SocketChannelImpl.finishConnect(Unknown Source)
	at io.ktor.network.sockets.SocketImpl.connect$ktor_network(SocketImpl.kt:50)
	at io.ktor.network.sockets.SocketImpl$connect$1.invokeSuspend(SocketImpl.kt)
	at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
	at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:101)
	at kotlinx.coroutines.internal.LimitedDispatcher$Worker.run(LimitedDispatcher.kt:113)
	at kotlinx.coroutines.scheduling.TaskImpl.run(Tasks.kt:89)
	at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:589)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:823)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:720)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:707)
If I replace localhost by 127.0.0.1 or my local IP address (and the server listens to it too), it works, so the issue seems related to
localhost
in default request
c
what platform are you running on?
o
macOS
a
Can you please try adding a trailing slash to the URL in the default request configuration?
o
I'm getting mad 😭 I can't reproduce it anymore… no clue what happens. I made some changes on backend side since, maybe it had some impacts but I can't see how 😞 Sorry for the noise.