首页 > 解决方案 > 从错误响应中获取数据时出现 java.io.IOException

问题描述

我已经为登录 API 实现了一个简单的POST请求。

val fuelRequest = Fuel.post(urlString)
    .header("Content-Type", "application/json")
    .header("Accept", "application/json")
    .jsonBody(UtilsString.getStringForDictionary(params))

fuelRequest.response() { _, response, result ->
    ...
    callback.onComplete(result)
}

当响应正常时,没有问题。当我尝试从错误请求中获取数据响应时,就会出现问题。我得到的数据是这样的:

{
    "code": 401,
    "error": "The specified credentials are invalid."
}

这带有 401 Unauthorized 响应。我只是想从 de request 中获取消息。如果我尝试response.data它会抛出Method throws 'java.io.IOException如果我尝试result.component()2.response它会抛出Method throws 'android.os.NetworkOnMainThreadException' 异常。无法评估 com.github.kittinunf.fuel.core.Response.toString()如果我尝试result.error.errorData抛出 Method throws 'java.io.IOException

任何线索我怎样才能得到回应?

标签: javakotlinfuel

解决方案


我复制了你的代码,如果我添加这个:

findViewById<FloatingActionButton>(R.id.fab).setOnClickListener { view ->
            val fuelRequest = Fuel.post("http://10.0.2.2:3000/")
                    .header("Content-Type", "application/json")
                    .header("Accept", "application/json")
                    .jsonBody(UtilsString.getStringForDictionary(params))

            fuelRequest.response() { _, response, _ ->
                println(String(response.data))
            }
}

我可以看到错误响应的正文。端点 10.0.2.2:3000 是一个小型 express.js 应用程序,它只提供一个小型 json。

app.post('/', function (req, res) {
  res.status(401).jsonp({ error: 'failed' })
});

推荐阅读