S
S
Sergey2021-01-23 12:28:12
Java
Sergey, 2021-01-23 12:28:12

Inappropriate blocking method call error on http request in Kotlin. What is the problem?

I study coroutines and a question arose. Sketched a simple function to get data from the network. But in Intelij IDEA highlights URL(url).openConnection() in yellow and displays a warning "Inappropriate blocking method call"

Tried to call like this

runBlocking { 
    getHttp("http://link.ru")
}

I set the suspend modifier for fun main - one fig highlights. Where is the mistake?
suspend fun getHttp(url: String): String {
    var txt = ""
    withContext(Dispatchers.IO) {
        with(URL(url).openConnection() as HttpURLConnection) {
            try {
                txt = inputStream.bufferedReader().readText()
            } catch (e:Exception) {
                e.printStackTrace()
            }
        }
    }
    return txt
}

As far as I understand, HttpUrlconnection is called blocking and can throw an exception in the form of an IOException. Along the way, the whole point of using coroutines then fades away, but this is not accurate ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2021-01-23
@Arpanet256

When you do that, the whole point of coroutines is lost. The trick is that when the coroutine is suspended, the thread is not blocked. And you use a blocking method inside the coroutine. Take another http client, ktor, he seems to be able to do this normally.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question