0
請問我可以在代碼中指出我的錯誤,我不能向攔截器添加頭「授權」。當我提出請求時,會拋出錯誤retrofit2.adapter.rxjava.HttpException:HTTP 401未授權。但是,當我添加標頭令牌爲每個請求爲什麼我無法將頭添加到攔截器requeset OkHttp上Retrofit?
@Header("Authorization") String token
然後它的工作。
這裏是我的代碼:
protected Retrofit retrofit;
protected OkHttpClient client;
protected T api;
protected UserCredential userCredential;
public RestClient(Class<T> type) {
if (client == null) {
synchronized (OkHttpClient.class) {
client = new OkHttpClient();
client.newBuilder().addInterceptor(chain -> {
Request original = chain.request();
Request.Builder builder = original.newBuilder();
if (GrabDoiApplication.getInstance().getCurrentCredentials() != null) {
String token = GrabDoiApplication.getInstance().getCurrentCredentials().getToken();
if (token != null) {
builder.addHeader("Authorization", token);
}
}
builder.method(original.method(), original.body());
return chain.proceed(builder.build());
}).build();
if (retrofit == null) {
synchronized (Retrofit.class) {
Retrofit.Builder retrofitBuilder = new Retrofit.Builder()
.baseUrl(Constants.GRABDOI_SERVER_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create());
retrofit = retrofitBuilder.build();
}
}
}
}
api = retrofit.create(type);
}
你是對的。非常感謝。 –