java.io.io从错误响应中获取数据时出现异常



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

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,它会抛出方法抛出"java.io.IOException">如果我尝试result.component()2.response,它抛出Method抛出"android.os.NetworkOnMainThreadException"异常。无法评估com.github.kittinunf.fuel.core.Respons.toString((如果我尝试result.error.errorData,它会抛出方法抛出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:3000是一个小型express.js应用程序,它只提供一个小型json。

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

我无法在注释中添加代码片段,但这是代码片段。你可以接受这样的请求,并根据你的用例做任何你想做的事情。

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, response, 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) {
""
}
}

您可以得到这样的响应,并对响应执行任何您想要的操作。

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,
@NotNull com.github.kittinunf.fuel.core.Response response,
String data) {
// data is a string, parse as using you fav json library
Log.d("Fuel.success", data);
}

最新更新