问题描述
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 未经授权的响应。我只是想从请求中获取消息。如果我尝试 response.data
它抛出 Method throw 'java.io.IOException 如果我尝试 result.component()2.response
它抛出 Method throw 'android.os.networkonmainthreadException' 异常。无法评估 com.github.kittinunf.fuel.core.Response.toString() 如果我尝试 result.error.errorData
它抛出 Method throw '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' })
});
,
你可以得到这样的响应,然后对响应做任何你想做的事情。
Fuel.post("https://api.chui.ai/v1/enroll")
.header(headers)
.body(json.toString(),Charset.forName("UTF-8"))
.responseString(new com.github.kittinunf.fuel.core.Handler<String>() {
@Override
public void failure(@NotNull com.github.kittinunf.fuel.core.Request request,@NotNull com.github.kittinunf.fuel.core.Response response,@NotNull FuelError error) {
Log.d("Fuel.failure",error.getMessage());
}
@Override
public void success(@NotNull com.github.kittinunf.fuel.core.Request request,String data) {
// data is a string,parse as using you fav json library
Log.d("Fuel.success",data);
}
,
我无法在评论中添加代码片段,但这里是代码片段。你可以接受这样的请求,然后根据你的用例做任何你想做的事情。
import com.github.kittinunf.fuel.Fuel
import com.github.kittinunf.fuel.core.FuelError
import com.github.kittinunf.result.Result
private class ResponseError(
val statusCode: Int,val statusMessage: String,val errorMessage: String
) : RuntimeException("[%d - %s] %s".format(statusCode,statusMessage,errorMessage))
fun main(args: Array<String>) {
val (request,result) = Fuel.post("http://httpbin.org/post").responseString()
when (result) {
is Result.Failure -> onError(result)
}
print("done")
}
/**
*
*/
fun onError(failureResult: Result.Failure<String,FuelError>) {
throw ResponseError(
statusCode = failureResult.error.response.statusCode,statusMessage = failureResult.error.response.responseMessage,errorMessage = failureResult.getErrorMessage())
}
/**
*
*/
private fun Result.Failure<String,FuelError>.getErrorMessage(): String {
return try {
val string = String(this.error.errorData)
print(string)
string
} catch (e: RuntimeException) {
""
}
}