繁体   English   中英

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

[英]java.io.IOException when getting data from error response

我已经为登录 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 throw 'java.io.IOException如果我尝试result.component()2.response它会抛出Method throw 'android.os.NetworkOnMainThreadException' 异常。 无法评估 com.github.kittinunf.fuel.core.Response.toString()如果我尝试result.error.errorData它会抛出 Method throws 'java.ZF98ED07A4D5F50F7DE1410D905ZF14Exception

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

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

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,
                                                @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);
                            }

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM