我正在使用Retrofit和OkHttp库在Android App上实现REST客户端。我的应用使用了安全的REST Web服务。我初始化Retrofit客户端的代码是:
...
OkHttpClient httpClient = new OkHttpClient.Builder()
.callTimeout(240, TimeUnit.SECONDS)
.readTimeout(240, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.addInterceptor(chain -> {
Request.Builder ongoing = chain.request().newBuilder();
ongoing.addHeader("Accept", "application/json");
if (token != null) {
ongoing.addHeader("Authorization", "Bearer: " + token);
} else {
//TODO block the call
}
return chain.proceed(ongoing.build());
}).addInterceptor(interceptor).build();
...
如果token
是null
,我需要阻止请求调用并直接返回401 response
。可能吗?谢谢。