0
我需要同步呼叫刷新Auth令牌,但我得到'NetworkOnMainThreadException'。Android Retrofit 2同步通話
@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
...
同步調用不會導致該異常最後定TokenAuthenticator您OkHttpClient
。在主線程的任何位置調用網絡都可以。請顯示一個[mcve]和完整的logcat –
另外,不是問題,但獲取令牌後,可以很輕鬆地通過'call.enqueue()'異步完成。 –