Retrofit 2 dynamic header

In Retrofit 2, when we need to add additional headers, we would just add an implementation of the Interceptor.

But sometimes, we only need to add a particular header for one API call, and the value is set dynamically at runtime. It's a bit tedious to add another interceptor just for that call.

The @Header annotation is really handy for this case. So we can pass a parameter annotated with @Header to the API call method. And Retrofit will take care of it.

Let's take look at an example:

@GET("/weather")
Observable<WeatherInfo> getWeather(@Header("foo") String value, Location location);

That would allow us to pass a String value as a request header for the getWeather API call. If the value is null, the foo header will just be omitted from the request.