java - 从错误响应中获取数据时出现 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
任何线索我怎样才能得到回应?
解决方案
我复制了你的代码,如果我添加这个:
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' })
});
推荐阅读
- dynamics-crm - Dynamics CRM - 将潜在客户转化为机会
- r - 在 R 中将 2-D 矩阵合并到 3-D 矩阵
- android - MultipartBody.Part 上传文件
- c++ - 什么是数组
这段代码中暗淡的意思是什么? - mysql - Mysql更新查询是否可以在set下有case语句和select语句
- asp.net-core - Asp.net Core - UseStaticFiles
- airflow - Airflow:如何将数据从父 dag 传递到子 dag(通过 xcom 或其他方式)
- javascript - 通过 JavaScript 敲击字符串
- html - 如何制作这种位于按钮旁边和其他元素上方的弹出窗口?
- spring - 仅当json有效时如何缓存