I have TokenAuthenticator class that implement Authenticator interface.
TokenAuthenticator class look like this:
import java.io.IOException;
import okhttp3.Authenticator;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;
import retrofit2.Call;
public class TokenAuthenticator implements Authenticator{
private String refreshTokenString;
private AuthenticationServiceApi serviceApi;
public TokenAuthenticator(ServiceGenerator serviceGenerator, String refreshTokenString) {
this.refreshTokenString = refreshTokenString;
serviceApi = (AuthenticationServiceApi) serviceGenerator.createService(AuthenticationServiceApi.class);
}
@Override
public Request authenticate(Route route, Response response) throws IOException {
RefreshToken refreshToken = new RefreshToken(refreshTokenString);
Call<RefreshTokenResponse> refreshTokenCall = serviceApi.refreshTokenSync(Constants.CONTENT_TYPE,refreshToken);
RefreshTokenResponse refreshTokenResponse = refreshTokenCall.execute().body();
if(refreshTokenResponse != null) {
return response.request().newBuilder()
.header("Authorization", refreshTokenResponse.accessToken)
.build();
}
return null;
}
}
And create service method is:
public <S> S createService(Class<S> serviceClass, AuthenticationProvider provider) {
System.out.println("createService");
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();
if (provider != null) {
okHttpClient.addInterceptor(chain -> {
Request original = chain.request();
Request.Builder request = original.newBuilder();
if (provider.accessToken() != null && !provider.accessToken().isEmpty()) {
request.addHeader("Authorization", provider.accessToken());
System.out.println("Authorization: " + provider.accessToken());
}
return chain.proceed(request.build());
});
TokenAuthenticator tokenAuthenticator = new TokenAuthenticator(this, provider.getRefreshToken());
okHttpClient.authenticator(tokenAuthenticator);
}
okHttpClient.addInterceptor(interceptor);
Retrofit.Builder reBuilder = createRetrofit(okHttpClient.build());
Retrofit retrofit = reBuilder.build();
return retrofit.create(serviceClass);
}
I get this exception:
HTTP FAILED: java.net.ProtocolException: Too many follow-up requests: 21
I'm used in retrofit and okHttp3 , What i need to do???
Ok i get the problem (Need to add Bearer to header request):
Need to change:
return response.request().newBuilder()
.header("Authorization", refreshTokenResponse.accessToken)
.build();
to this code:
return response.request().newBuilder()
.header("Authorization", "Bearer " + refreshTokenResponse.accessToken)
.build();