gpt4 book ai didi

java - 如何在Retrofit2中添加标题

转载 作者:行者123 更新时间:2023-12-01 19:16:27 24 4
gpt4 key购买 nike

我很困惑,我已将 token 保存在 SharedPrefernce 中,当我尝试获取用户名时,即使我已经使用了 Header 和 Sharedpref token ,我仍然无法清空对象首选项。也许我的错误是没有给 Header 进行改造。在这里我很困惑父亲添加标题。我已经使用了现有的引用资料,但它不起作用。我恳求您是否有出路,我真的希望您能帮助我。

RetrofitClient.java

public class RetrofitClient {

SharedPrefManager sharedPrefManager;
private static Retrofit retrofit = null;

public static Retrofit getClient(String baseUrl){
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.build();

if (retrofit == null){
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
}
return retrofit;
}
}

此 token 保存

SharedPrefManager sharedPrefManager;
sharedPrefManager.getSPToken()

最佳答案

这是示例改造客户端

 public class RetrofitClient {


private static Retrofit retrofit = null;

public static Retrofit getClient(String baseUrl){
HeaderInterceptor interceptor = new HeaderInterceptor();
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.build();

if (retrofit == null){
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
}
return retrofit;
}
}

适合您的用例的拦截器。

public class HeaderInterceptor implements Interceptor {

SharedPrefManager sharedPrefManager = new SharedPrefManager();

@Override
public Response intercept(Chain chain) throws IOException {

Request originalRequest = chain.request();

Request newRequest = originalRequest.newBuilder()
.header("Language", sharedPrefManager.getSPToken())
.build();

return chain.proceed(newRequest);

}
}

关于java - 如何在Retrofit2中添加标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59411574/

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