我们的团队决定采用Retrofit 2.0,我正在做一些初步的研究.我是这个图书馆的新手.
我想知道如何使用拦截器通过我们的Android应用程序中的Retrofits 2.0添加自定义标头.关于使用拦截器在Retrofit 1.X中添加标头有很多tutorials,但由于API在最新版本中发生了很大的变化,我不确定如何在新版本中调整这些方法.此外,Retrofit尚未更新其新文档.
例如,在以下代码中,我应该如何实现Interceptor类来添加额外的头文件?此外,undocumented Chain
object究竟是什么?何时会调用intercept()?
OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
// How to add extra headers?
return response;
}
});
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_API_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
解决方法:
看一下这个.
public class HeaderInterceptor
implements Interceptor {
@Override
public Response intercept(Chain chain)
throws IOException {
Request request = chain.request();
request = request.newBuilder()
.addHeader("appid", "hello")
.addHeader("deviceplatform", "android")
.removeHeader("User-Agent")
.addHeader("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0")
.build();
Response response = chain.proceed(request);
return response;
}
}
科特林
class HeaderInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response = chain.run {
proceed(
request()
.newBuilder()
.addHeader("appid", "hello")
.addHeader("deviceplatform", "android")
.removeHeader("User-Agent")
.addHeader("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0")
.build()
)
}
}