燃料 httpGet() 响应字符串,失败原因:com.github.kittinunf.fuel.core.BubbleFuelError: null。

3

问题

我想通过使用Fuel作为Httpclient进行同步调用API来获取get请求的结果。 我正在使用在Android(Anko)项目中使用Fuel。 这个调用只是一个简单的get请求,但总是失败并显示以下错误:

Failure: com.github.kittinunf.fuel.core.BubbleFuelError: null

Caused by: com.github.kittinunf.fuel.core.BubbleFuelError: null

背景

我想编写一个函数,以使用Fuel返回一个简单get请求的结果。但是我无法同步检索结果。

我无法在互联网上找到有关此主题的任何有用信息。

我尝试使用协程等待结果并使用awaitStringResponse函数。-->未按预期工作。

刚刚回应了一个涵盖此主题的Github问题(标记为bug)。 https://github.com/kittinunf/fuel/issues/606

是否有一些解决方法?

代码示例

这段代码有效:

requestUrl.httpGet().responseString { _, _, result ->
     when (result) {
          is Result.Success -> {
             // do something on success
          }
          is Result.Failure -> {
             // do something on fail
          }
     }
}

但是使用这个函数,我无法返回结果。

这段代码不起作用。

val (_,_,result)= Fuel.get(requestUrl).responseString()
1个回答

0

我找到了一种使用 Kotlin 协程解决这个问题的方法。

fun doRequest() = runBlocking {
    val (_, _, result) = Fuel.get("https://jsonplaceholder.typicode.com/posts/1").awaitStringResponse()
    result
}

使用runBlocking将会阻塞当前线程,直到它完成。

来源:https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/run-blocking.html

当您不想阻塞当前线程时,可以像这样在新线程中启动此函数:

Thread(
    Runnable {
      val result = doRequest()
      Log.e("Result", result)
    }
).start()

如果有人知道更好的处理方法,请展示你的解决方案。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接