我有TokenAuthenticator类,它实现了Authenticator接口。
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;
}
}
创建服务方法是:
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,我需要做什么???
答案 0 :(得分:2)
好的,我遇到了问题(需要将Bearer添加到标头请求中):
需要改变:
return response.request().newBuilder()
.header("Authorization", refreshTokenResponse.accessToken)
.build();
到此代码:
return response.request().newBuilder()
.header("Authorization", "Bearer " + refreshTokenResponse.accessToken)
.build();