简体   繁体   English

Retrofit 协程状态码 205 正文 Null

[英]Retrofit Coroutine Status Code 205 Body Null

I'm having difficulty on getting the response data from server.我很难从服务器获取响应数据。

I have a validation scenario that server throws an error if a user already exist, somehow someway, the api developer decided to use 205 as status code instead of usual 200.我有一个验证场景,如果用户已经存在,服务器会抛出错误,不知何故,api 开发人员决定使用 205 作为状态码而不是通常的 200。

The problem is everytime I'm calling the API, the body() and errorBody() returns null As suggested, I used the Response to get the response.问题是每次我调用 API 时,body() 和 errorBody() 都会返回 null 正如建议的那样,我使用 Response 来获取响应。

isSuccessful() is returning true, I can see on my logcat the raw Json response from server but return both null on body() and errorBody(), any idea what seems to be the error here? isSuccessful() 正在返回 true,我可以在我的 logcat 上看到来自服务器的原始 Json 响应,但在 body() 和 errorBody() 上返回 null,知道这里的错误是什么吗?

Thanks In Advance.提前致谢。

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
    }

Retrofit skips the converter if the status code is 204 or 205.如果状态码为 204 或 205,Retrofit 会跳过转换器。

You can try adding an OkHttp Interceptor which would convert the server's 205 code to 200 before Retrofit works on it.您可以尝试添加一个 OkHttp 拦截器,它会在 Retrofit 处理它之前将服务器的 205 代码转换为 200。

Like this:像这样:

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
        }
    }
}

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

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