我们的团队决定采用 Retrofit 2.0, 而我正在对此进行一些初步研究。我是这个图书馆的新手。
我想知道如何在Android应用中interceptor通过 Retrofits 2.0 添加自定义标题。在Retrofit 1.X中有许多关于使用添加标题的教程interceptor,但是由于API在最新版本中已经发生了很大变化,因此我不确定如何在新版本中适应这些方法。另外,Retrofit尚未更新其新文档。
interceptor
例如,在以下代码中,如何实现Interceptor该类以添加额外的标头?此外,未记录的Chain对象到底是什么?何时会intercept()被调用?
Interceptor
Chain
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() .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() ) } }