Reputation: 47
Trying add an interceptor to add headers to requests with okhttp3 and retrofit2. I noticed the headers weren't being added to requests and my system.out.println debug line was never getting called. No idea why but here's my code:
creating the service:
OkHttpClient client = new OkHttpClient();
client.newBuilder()
.addInterceptor(new ServiceInterceptor(context))
.authenticator(new MyAuthenticator(context))
.build();
service = (new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build())
.create(Service.class);
ServiceInterceptor:
public class ServiceInterceptor implements Interceptor {
private final Context context;
public ServiceInterceptor(Context context){
this.context = context;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
System.out.println("Interceptor");
if(request.header("No-Authentication") == null){
request = request.newBuilder()
.addHeader("User-Agent", "APP NAME")
.addHeader("Authorization", "bearer " + PreferenceManager.getDefaultSharedPreferences(context).getString("access_token", ""))
.build();
}
return chain.proceed(request);
}
}
Not exactly part of the question but my authenticator is never being called either...:
public class MyAuthenticator implements Authenticator {
private Context context;
public MyAuthenticator(Context context){
this.context = context;
}
@Override
public Request authenticate(Route route, Response response) throws IOException {
//blah blah refresh token here...
return null;
}
}
Upvotes: 1
Views: 2489
Reputation: 32026
You set client
to a default OkHttpClient
. You create a new client from that client using newBuilder()
, but don't assign it to anything. If you aren't using the first client, you should just allocate a builder the first time --
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new ServiceInterceptor(context))
.authenticator(new MyAuthenticator(context))
.build();
Upvotes: 5