Retrofit request headers

How to add and change request headers in a Retrofit request

For a more complete and in-depth explanation, check out our complete Retrofit course

Download the starter project here

Github repository

Headers can be passed both in the request and in the response. What we’re going to talk about here is how we can pass our own headers in the request of our application.

As always, we have multiple options

Static headers

Firstly we have the static option. If we have a header that needs to be passed for every single invocation of a certain request, whatever the parameters, then we have the option to put the header or headers at the top in an annotation.

Updating the ApiCall interface we get

@Headers(“Cache-Control: max-age=3600”, “user-agent: abc”)

@GET(“apiCall”)

fun callHeadersStatic(): Call<ApiCallResponse>

We use the @Headers annotation. We can pass as many headers as you want in the annotation. We have a cache control header with a duration of 1 hour, and a user agent abc.

In order for the app to use these headers we also need to update the ApiCallService class

fun call() = api.callHeadersStatic()

headers_static

Dynamic headers

We also have the option to use dynamic headers. In this case headers are not set at the top in an annotation, but instead we pass an @Header annotation inside the parameters of the function, we will provide the name of the header as well as the value in a variable.

@GET(“apiCall”)

fun callHeadersDynamic(@Header(“user-name”) userName: String): Call<ApiCallResponse>

Updating the ApiCallService class and running the app, that gives us

fun call() = api.callHeadersDynamic(“Michael”)

headers_dynamic

Multiple headers

If we need to provide a variable number of headers, we don’t want to go into the function to change it every single time. In this case we have the annotation @HeaderMap that takes a variable of type Map that contains the name of the header and the value. Putting that in code we have

@GET(“apiCall”)

fun callHeadersMultiple(@HeaderMap headers: Map<String, String>): Call<ApiCallResponse>

And updating the ApiCallService class we have

fun call() = api.callHeadersMultiple(hashMapOf(Pair(“user-agent”, “abc”),

Pair(“username”, “John”)))

headers_multiple

For a more complete and in-depth explanation, check out our complete Retrofit course

Close Bitnami banner
Bitnami