我有一个解决方案。请尝试以下代码。
制作类:TokenAuthenticator.java
import android.content.Context;
import android.support.annotation.Nullable;
import com.dmlllc.insideride.common.Preferences;
import com.dmlllc.insideride.model.AccessToken;
import com.dmlllc.insideride.restModel.RestResponse;
import com.dmlllc.insideride.restModel.requestModel.AccessTokenReq;
import java.io.IOException;
import okhttp3.Authenticator;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;
public class TokenAuthenticator implements Authenticator {
private Context context;
public TokenAuthenticator(Context context) {
this.context = context;
}
@Nullable
@Override
public Request authenticate(Route route, Response response) throws IOException {
// Refresh your access_token using a synchronous api request
AccessTokenReq accessTokenReq = new AccessTokenReq(Preferences.getPreferenceString(context, Preferences.USERNAME_FOR_TOKEN, ""),
Preferences.getPreferenceString(context, Preferences.PASSWORD_FOR_TOKEN, ""));
try {
retrofit2.Response<RestResponse<AccessToken>> tokenResponse = Global.initRetrofit(context).getAccessToken(accessTokenReq).execute();
if (tokenResponse.body() != null) {
if (tokenResponse.body().getResStatus().equals("success")) {
SessionManager sessionManager = new SessionManager(context);
sessionManager.storeToken(tokenResponse.body().getResults().getYourAccessToken());
Preferences.setPreferenceString(context, Preferences.ACCESS_TOKEN, tokenResponse.body().getResults().getYourAccessToken());
}
}
}catch (Exception e){
e.printStackTrace();
}
// Add new header to rejected request and retry it
return response.request().newBuilder()
.header("Authorization", Preferences.getPreferenceString(context, Preferences.ACCESS_TOKEN, ""))
.build();
}
}
然后在你的改造方法中使用这个类,就像:
public static RestApi initRetrofit(Context context) {
// For logging request & response (Optional)
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
TokenAuthenticator tokenAuthenticator = new TokenAuthenticator(context);
OkHttpClient client = new OkHttpClient.Builder()
.authenticator(tokenAuthenticator)
.addInterceptor(loggingInterceptor)
.connectTimeout(1, TimeUnit.MINUTES)
.writeTimeout(1, TimeUnit.MINUTES)
.readTimeout(1, TimeUnit.MINUTES)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
return retrofit.create(RestApi.class);
}
希望它也能帮助你。:)
快乐编码...!!!