Home > database >  Why I can't read text from URL with KTOR client?
Why I can't read text from URL with KTOR client?

Time:02-04

I want to read a text from a URL with KTOR client.

suspend fun fetch() : String {
    val client = HttpClient(CIO)
    return client.get(ENDPOINT)
}

but it gives me a Type mismatch. Required:String. Found:HttpResponse.

I did the same thing with:

suspend fun fetch() : String {
    return URL(ENDPOINT).readText()
}

how can do it with KTOR client?

CodePudding user response:

See the doc on receiving responses.

Since Ktor 2, client.get(...) returns an HttpResponse instance, and then you can read the body explicitly using .body():

suspend fun fetch() : String {
    val client = HttpClient(CIO)
    return client.get(ENDPOINT).body()
}

The body() method is generic and the return type depends on the expected expression type. You can make it explicit by using .body<String>(), especially in contexts where the compiler cannot guess.

Note that you shouldn't create a new client on the fly every time you make a request. Clients need resources like thread pools, and it's best if they are reused.

CodePudding user response:

You can use the "receive" function in Ktor to retrieve the text content of a URL.

 suspend fun fetch(): String {
        val client = HttpClient(CIO)
        val response = client.get<HttpResponse>(ENDPOINT)
        return response.receive<String>()
    }
  • Related