OKHttp身份验证器不能与翻新一起使用暂停乐趣

时间:2019-12-11 17:03:55

标签: android retrofit2 okhttp kotlin-coroutines authenticator

我最近将Retrofit更新为2.7.0,并将OKHttp更新为3.14.4,以利用Retrofit接口上的暂停乐趣。

除此之外,我还尝试为刷新令牌逻辑实现Authenticator。

这是改造界面

interface OfficeApi {
    @Authenticated
    @POST
    suspend fun getCharacter(): Response<CharacterResponse>
}

这是我的身份验证器

class CharacterAuthenticator : Authenticator {

    override fun authenticate(
        route: Route?,
        response: Response
    ): Request? {
        if (responseCount(response) >= 2) return null

        return response.request()
                        .newBuilder()
                        .removeHeader("Authorization")
                        .addHeader("Authorization", "Bearer $newToken")
                        .build()

        return null
    }

    private fun responseCount(response: Response?): Int {
        var result = 1
        while (response?.priorResponse() != null) result++
        return result
    }

}

这是改造有趣的电话

    override suspend fun getCharacter() = safeApiCall(moshiConverter) {
        myApi.getCharacter()
    }

这是safeApiCall

suspend fun <T> safeApiCall(
    moshiConverter: MoshiConverter,
    apiCall: suspend () -> Response<T>
): Result<T?, ResultError.NetworkError> {
    return try {
        val response = apiCall()
        if (response.isSuccessful) Result.Success(response.body())
        else {
            val errorBody = response.errorBody()
            val errorBodyResponse = if (errorBody != null) {
                moshiConverter.fromJsonObject(errorBody.string(), ErrorBodyResponse::class.java)
            } else null

            Result.Error(
                ResultError.NetworkError(
                    httpCode = response.code(),
                    httpMessage = response.message(),
                    serverCode = errorBodyResponse?.code,
                    serverMessage = errorBodyResponse?.message
                )
            )
        }
    } catch (exception: Exception) {
        Result.Error(ResultError.NetworkError(-1, exception.message))
    }
}

身份验证器工作正常,尝试刷新令牌两次,然后放弃。问题是:当放弃(返回null)时,翻新(safeApiCall函数)的执行不会继续。通话是否成功,我没有任何反馈。

使用Authenticator和Coroutines suspend fun是否有问题?

2 个答案:

答案 0 :(得分:1)

这不是无限循环吗?

while (response?.priorResponse() != null)

不是吗

var curResponse: Response? = response
while (curResponse?.priorResponse() != null) {
    result++
    curResponse = curResponse.priorResponse()
}

答案 1 :(得分:-2)

删除暂停,请尝试以下代码

fun getCharacter(): Response<CharacterResponse>