gpt4 book ai didi

java - 改造2:添加RequestInterceptor

转载 作者:太空宇宙 更新时间:2023-11-04 12:35:44 24 4
gpt4 key购买 nike

伙计们,请尝试从retrofit 1升级到retrofit 2,但我很难为所有请求添加请求拦截器。在 retrofit 1 中,我通过做这样的事情来实现它;

public static <S> S createService(Class<S> serviceClass, final String token) {
RestAdapter.Builder builder = new RestAdapter.Builder()
.setEndpoint(Constant.APP_URL);
builder.setRequestInterceptor(new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
request.addHeader("token", token);
}
});
RestAdapter adapter = builder.build();

return adapter.create(serviceClass);
}

但是我在retrofit 2中无法解决这个问题...请问有人可以解决我的问题吗?

最佳答案

在您的依赖项 block 中添加:

compile 'com.squareup.okhttp3:logging-interceptor:3.2.0'

在您的Retrofit服务类中添加:

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.build();

然后添加:

    Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL)
.client(client) // this is the line you care about
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(JacksonConverterFactory.create())
.build();

关于java - 改造2:添加RequestInterceptor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37368657/

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