【问题标题】:Retrofit Coroutine Status Code 205 Body Null改造协程状态码 205 Body Null
【发布时间】:2020-09-07 20:21:56
【问题描述】:

我在从服务器获取响应数据时遇到了困难。

我有一个验证场景,如果用户已经存在,服务器会抛出错误, 不知何故,api 开发者决定使用 205 作为状态码,而不是通常的 200。

问题是每次我调用 API 时,body() 和 errorBody() 都会返回 null 按照建议,我使用 Response 来获取响应。

isSuccessful() 正在返回 true,我可以在我的 logcat 上看到来自服务器的原始 Json 响应 但是在 body() 和 errorBody() 上都返回 null,知道这里的错误是什么吗?

提前致谢。

override suspend fun safeRegisterAccount(registerBody: RegisterBody): LiveData<out Wrapper<RegisterResponse>?> {
        val result = MutableLiveData<Wrapper<RegisterResponse>>()
        try {
            val account = networkService.safeRegister(registerBody)
            val wrapper = Wrapper<Token>()  
            wrapper.objectData = account.body()?.objectData
            wrapper.status = account.code()
            result.postValue(wrapper)
        } catch (ex: Exception) {
            plantLog(ex.message)
        }

        return result
    }

【问题讨论】:

  • 响应码 200..299 表示成功。所以无论如何它应该是成功的。您能否显示获取响应并检查isSuccessfulbody() 的代码?。
  • @Antonio 肯定会更新帖子。
  • 你检查是否有任何异常被捕获?
  • 如果没有通过异常。它通常与 200 状态相同
  • 所以您的实时数据正在被观察到但 objectData 为空?

标签: android kotlin networking retrofit kotlin-coroutines


【解决方案1】:

如果状态码是 204 或 205,Retrofit 会跳过转换器。

您可以尝试添加一个 OkHttp 拦截器,它会在 Retrofit 处理它之前将服务器的 205 代码转换为 200。

像这样:

class BodyInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val response = chain.proceed(chain.request())

        if (response.code == 204 || response.code == 205) {
            return response
                .newBuilder()
                .code(200)
                .body(response.body)
                .build()
        } else {
            return response
        }
    }
}

【讨论】:

  • 救命伴侣!让我试试这个,谢谢你的帮助!
猜你喜欢
  • 2021-07-11
  • 2016-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-12
  • 2014-05-29
  • 1970-01-01
  • 2021-01-28
相关资源
最近更新 更多