Android Retrofit 2同步通话

时间:2017-10-16 06:43:22

标签: android kotlin retrofit2

我需要同步调用来刷新Auth令牌,但我得到了“ NetworkOnMainThreadException ”。

@Synchronized
fun refreshToken(): String? {
    val refreshToken = AuthService.getRefreshToken(context)
    var id_token: String? = null

    val call = apiService.refreshToken("refresh_token", refreshToken)
            val response = call.execute()

            id_token = response.body()

            if (id_token != null)
            {
                AuthService.saveTokens(context, id_token)
            }
        })

    return id_token
}

我该如何避免'NetworkOnMainThreadException'?

D/OkHttp: --> POST https://localhost/api/auth/refresh http/1.1 (372-byte body)
D/OkHttp: <-- HTTP FAILED: android.os.NetworkOnMainThreadException
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.test, PID: 1537
                  android.os.NetworkOnMainThreadException
                  ...

1 个答案:

答案 0 :(得分:0)

使用Retrofit实现refreshToken的最佳方法是使用Authenticator。

class TokenAuthenticator : Authenticator {
    override fun authenticate(route: Route?, response: Response?): Request {
        //call your Refresh Token here
    }
}

最后将TokenAuthenticator设置为您的OkHttpClient

val httpClient : OkHttpClient.Builder = OkHttpClient.Builder()
httpClient.authenticator (TokenAuthenticator())

如果你坚持使用你的方式,你应该在另一个线程中调用改装api