Authenticator インターフェイスを実装する TokenAuthenticator クラスがあります。
TokenAuthenticator クラスは次のようになります。
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;
}
}
create service メソッドは次のとおりです。
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);
}
私はこの例外を受け取ります:
HTTP FAILED: java.net.ProtocolException: Too many follow-up requests: 21
私は改造と okHttp3 で使用されています。何をする必要がありますか???