我使用 Ktor 和这样的线路myentity = client.get(url)
从 API 响应获取并反序列化我的实体。当 API 返回某些内容时它工作正常,但是一旦 API 没有任何可返回的内容并发送 HTTP 204 响应,它就会失败并显示 io.ktor.client.call.NoTransformationFoundException。
我想找到一种方法使 client.get() 返回 null 而不是抛出该异常。我非常寻找解决方案,但未能找到。看起来HttpResponseValidator
在 HttpClient 的初始化中可能会有所帮助,但我只找到了一种如何从中抛出另一个异常的方法,但不了解如何更改返回值。
你可以抓住NoTransformationFoundException
并分配null
to myentity
如果抛出异常。这是一个例子:
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.engine.okhttp.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.request.*
import io.ktor.serialization.kotlinx.json.*
import kotlinx.serialization.json.Json
suspend fun main() {
val client = HttpClient(OkHttp) {
install(ContentNegotiation) {
json(Json { ignoreUnknownKeys = true })
}
}
val response = try {
client.get("https://httpbin.org/status/204").body<HttpBin>()
} catch (cause: NoTransformationFoundException) {
null
}
println(response?.origin)
}
@kotlinx.serialization.Serializable
class HttpBin(val origin: String)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)