Recently, I need to add a header in the project, and then I would like to think about how to add a header in retrofit
(1) Add a header parameter using annotation
public interface ApiService { @Headers("Cache-Control: max-age=560000") @GET("/data") Call<List<Data>> getData(); }
(2) Add multiple header parameters using annotations
public interface ApiService { @Headers({ "Accept: application/.+json", "User-Agent: YourAppName" }) @GET("/data/{user_id}") Call<Data> getData(@Path("user_id") long userId); }
(3) The method of using annotations, the header parameters are different each time, dynamically add the header
public interface ApiService { @GET("/data") Call<List<Data>> getData(@Header("Content-Range") String contentRange); }
(4) Adding header in the code requires using an interceptor
client = new (); (new Interceptor() { @Override public Response intercept( chain) throws IOException { Request original = (); Request request = () .header("User-Agent", "YourAppName") .header("Accept", "application/.+json") .method((), ()) .build(); return (request); } } OkHttpClient httpClient = (); Retrofit retrofit = new () .baseUrl(Constant.BASE_URL) .addConverterFactory(()) .client(httpClient) .build();
In fact, we look at the addInterceptor method above, and it doesn't matter which interceptor is in front and which one is in the back. But the fact is, if mHttpLoggingInterceptor is placed in front, the heanders added to the subsequent interceptor will not take effect. When we use addInterceptor to add network interceptor, we must put the network interceptor in front.
Use addNetworkInterceptor
When we use network request interceptor, we directly use the addNetworkInterceptor method to add, instead of addInterceptor to add.
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.