Search code examples
kotlin-multiplatformktor

Ktor KMP REQUEST failed with exception: kotlin.IllegalStateException: Invalid url


I have a KMP project. I am implementing Ktor for network request. My android version is working completely fine. But when I run iOS version of the app, it gives below error:

REQUEST https://example.com/api/v1/history failed with exception: kotlin.IllegalStateException: Invalid url: https://example.com/api/v1/history

Does anyone know any reason for which this error might occur? I think there is no problem with the URL as it's working fine on Android version of the app. I also have tested the URL with other ways too.

My setup of HttpClient is as below

HttpClient {
        expectSuccess = true

        defaultRequest {
            host = "example.com/api/v1"
            url {
                protocol = URLProtocol.HTTPS
            }
            contentType(ContentType.Application.Json)

            // API Key
            header("X-API-KEY", BuildKonfig.API_KEY)
        }

        install(HttpTimeout) {
            requestTimeoutMillis = 15_000
            connectTimeoutMillis = 15_000
        }

        install(ContentNegotiation) {
            json(Json {
                ignoreUnknownKeys = true
                prettyPrint = true
            })
        }

        install(Logging) {
            level = LogLevel.ALL
            logger = object : Logger {
                override fun log(message: String) {
                    Napier.i(tag = "ApiLog", message = message)
                }
            }
        }.also {
            Napier.base(DebugAntilog())
        }
    }

And in the calling side, I'm calling my API like below

client.get("history").body()

Solution

  • I have got the solution. The problem was, I was settings host = "example.com/api/v1" in my HttpClient configuration, and was calling client.get("history").body() in my request side.
    With below changing, my iOS version of the app finally worked

    host = "example.com/api/v1"
    

    to

    host = "example.com"
    

    and in request side

    client.get("history").body()
    

    to

    client.get("api/v1/history").body()