2017-10-16 114 views
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 
        ... 
+0

同步調用不會導致該異常最後定TokenAuthenticator您OkHttpClient

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

。在主線程的任何位置調用網絡都可以。請顯示一個[mcve]和完整的logcat –

+0

另外,不是問題,但獲取令牌後,可以很輕鬆地通過'call.enqueue()'異步完成。 –

回答

0

使用Authenticator實現refreshToken的最佳方式是使用Authenticator。

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

如果你堅持要用自己的方式,你應該調用API改造在另一個線程