簡體   English   中英

Retrofit 協程狀態碼 205 正文 Null

[英]Retrofit Coroutine Status Code 205 Body Null

我很難從服務器獲取響應數據。

我有一個驗證場景,如果用戶已經存在,服務器會拋出錯誤,不知何故,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
    }

如果狀態碼為 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
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM