简体   繁体   中英

Kotlin Fuel blocking mode GET http request always fails

Until now, I've been using Fuel's async GET http requests and everything works fine.

I now need to send the request in a blocking mode since I need the result before the app continues to run.

Here is a very simple GET http request in blocking mode for testing purposes:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    override fun onStart() {
        super.onStart()

        val (_, _, result) = "https://httpbin.org/get"
            .httpGet()
            .responseString()

        when (result) {
            is Result.Failure -> {
                val ex = result.getException()
                Log.e("FUEL", ex.toString())
            }
            is Result.Success -> {
                val data = result.get()
                tvTest.text = data
            }
        }
    }
}

I always have the error message in LogCat, which means that I always get a Result.Failure . Can anyone help on this?

Thank you very much for your time.

I don't understand it all yet, but I got it working. Here's what I did.

  1. Added implementation 'com.github.kittinunf.fuel:fuel-coroutines:2.2.1' to my app build.gradle
  2. Changed.responseString() to.awaitStringResponse()
  3. surrounded the code with runBlocking{ }

So give this a try:

runBlocking {
    val (_, _, result) = "https://httpbin.org/get"
        .httpGet()
        .awaitStringResponse()

    when (result) {
        is Result.Failure -> {
            val ex = result.getException()
            Log.e("FUEL", ex.toString())
        }
        is Result.Success -> {
            val data = result.get()
            tvTest.text = data
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM