如何使用带有Fuel的异步HTTP GET获取响应的主体 [英] How to get the body of the response using async HTTP GET with Fuel

查看:140
本文介绍了如何使用带有Fuel的异步HTTP GET获取响应的主体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Fuel进行以下HTTP GET调用:

I have the following HTTP GET call using Fuel:

uri.httpGet().responseObject<Array<Data>> { _, response, result ->
        result.fold(success = {
            getSuccessMessage()
        }, failure = {
            val msg = "Error: ${it.message}"
            val errorData = response.data.toString() //always throws Exception               
        })

当我接到未经授权的呼叫(返回状态代码401 )时,我需要具有响应正文.

When I get an unauthorized call (returning status code 401), I need to have the response body.

当我使用异步方式时,我不幸的是,当我尝试读取响应时,总是会得到一个android.os.NetworkOnMainThreadException.

Unfortunately, I always get a android.os.NetworkOnMainThreadException when I try to read the response.

我如何正确获取消息?

推荐答案

对于网络上的主线程异常,这是基于协程的解决方案.它也处理网络调用中的错误.

For network on main thread exception ,this is the solution based on coroutine.It handles the error on network call as well.

在您的ApiService.kt文件中具有如下包装函数.

In your ApiService.kt file have a wrapper function like below.

class ApiService {
    suspend fun getAsyncWay(url: String): Any? {
        return withContext(Dispatchers.IO) {

            val (request, response, result) = Fuel.get(url)
                .header("Accept", "application/json")
                .responseString()

            when (result) {
                is Result.Failure -> {
                    println("Inside the Fuel Failure result  ${String(response.data)}")
                    return@withContext String(response.data)
                }
                is Result.Success -> {
                    val data = result.get()
                    println("Inside the Fuel Data Success result $data") // you can also use ${String(response.data)
                    return@withContext data // response.statusCode is also available if we need to go that path.
                }
            }
        }
    }
  }

然后在您的activity中,您可以调用类似这样的URL.

Then in your activity, you can call URL something like this.


    val job = Job()
    val ioScope = CoroutineScope(Dispatchers.IO + job)

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

       ioScope.launch {
            val url ='http://github.com/commits/blah'
            val commitsList = ApiService().getAsyncWay(url)
            println("commitsList list in the coroutine   $commitsList")
            textView.setText(commitsList);
        }
       }

这篇关于如何使用带有Fuel的异步HTTP GET获取响应的主体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆