尝试使用okhttp3和retrofit2添加拦截器以向请求添加标头。我注意到标题没有被添加到请求中,我的system.out.println调试行从未被调用过。不知道为什么,但这是我的代码:
创建服务:
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);
}
}
不完全是问题的一部分,但我的身份验证员从未被调用过......:
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;
}
}
答案 0 :(得分:3)
您将client
设置为默认OkHttpClient
。您使用newBuilder()
从该客户端创建新客户,但不要将其分配给任何内容。如果您没有使用第一个客户端,则应该首次分配构建器 -
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new ServiceInterceptor(context))
.authenticator(new MyAuthenticator(context))
.build();