gpt4 book ai didi

android - 为什么我不能在 Retrofit 中向拦截器请求 OkHttp 添加 header ?

转载 作者:行者123 更新时间:2023-11-29 19:17:24 24 4
gpt4 key购买 nike

能否请您指出我在代码中的错误,我无法将 header “授权”添加到拦截器。当我发出请求时,它会抛出错误 retrofit2.adapter.rxjava.HttpException: HTTP 401 Unauthorized 。但是当我为每个请求添加 Header token 时

@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);
}

最佳答案

您可以尝试将对静态方法的访问放在拦截器主体之外:

    public RestClient(Class<T> type) {
if (retrofit != null) {
return;
}
synchronized (OkHttpClient.class) {
client = new OkHttpClient();
OkHttpClient.Builder builder = client.newBuilder();
final String token;
if (GrabDoiApplication.getInstance().getCurrentCredentials() != null &&
(token = GrabDoiApplication.getInstance().getCurrentCredentials().getToken()) != null) {
builder.addInterceptor(chain -> {
Request.Builder builder = chain.request().newBuilder();
builder.addHeader("Authorization", token);
builder.method(original.method(), original.body());
return chain.proceed(builder.build());
});
}
client = builder.build();

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);
}

关于android - 为什么我不能在 Retrofit 中向拦截器请求 OkHttp 添加 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43096025/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com