我们在Android应用中使用Retrofit与OAuth2安全服务器进行通信.一切都很好,我们使用RequestInterceptor在每次调用时包含访问令牌.但是,有时候,访问令牌将过期,并且需要刷新令牌.当令牌过期时,下一个调用将返回一个未授权的HTTP代码,因此很容易监控.我们可以通过以下方式修改每个Retrofit调用:在失败回调中,检查错误代码,如果它等于Unauthorized,则刷新OAuth令牌,然后重复Retrofit调用.但是,为此,应修改所有呼叫,这不是一个易于维护的好解决方案.有没有办法在不修改所有Retrofit调用的情况下执行此操作?
我正在使用Retrofit和OkHttp库.所以Authenticator如果获得401响应,我有哪个authanticate用户.
我build.gradle是这样的:
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
compile 'com.squareup.okhttp3:okhttp:3.1.2'
Run Code Online (Sandbox Code Playgroud)
我的习惯Authenticator在这里:
import java.io.IOException;
import okhttp3.Authenticator;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;
public class CustomAuthanticator implements Authenticator {
@Override
public Request authenticate(Route route, Response response) throws IOException {
//refresh access token via refreshtoken
Retrofit client = new Retrofit.Builder()
.baseUrl(baseurl)
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService service = client.create(APIService.class);
Call<RefreshTokenResult> refreshTokenResult=service.refreshUserToken("application/json", "application/json", "refresh_token",client_id,client_secret,refresh_token);
//this is syncronous retrofit request
RefreshTokenResult refreshResult= refreshTokenResult.execute().body();
//check if response equals 400 , …Run Code Online (Sandbox Code Playgroud)