In Retrofit, when do you use @Headers, @Header and @HeaderMap on a service method, and how do the headers they add combine?
answer
- static versus per-call values
- nothing overwrites anything
- null header disappears
- Content-Type is special
- every request belongs elsewhere
basics
~20 s@Headers adds fixed headers to one method, @Header sets one header from an argument (null omits it) and @HeaderMap adds many from a map. Apart from Content-Type, same-named headers are all sent, never overwritten. Headers for every request belong in an OkHttp interceptor.
solid answer
~40 s`@Headers("Accept: application/vnd.tracker.v2+json")` is a method annotation for **static** headers on that one endpoint, each written as `Name: Value`. `@Header("Accept-Language")` on a parameter sets a **per-call** value; `null` omits the header and a `List` sends one header per non-null item. `@HeaderMap` takes a `Map<String, ...>` or OkHttp's `Headers` for a variable set, and rejects a `null` map, key or value. Apart from `Content-Type`, none of them replaces another: if `@Headers` and `@Header` both name `Accept`, both lines are sent. A `Content-Type` given this way is not added as a second line; it overrides the body's media type. Non-ASCII values are refused unless `allowUnsafeNonAsciiValues = true` (Retrofit 2.10.0). A header every call needs, such as a bearer token, goes in an OkHttp interceptor rather than on each method.
code
kotlin · 15 linesinterface IssueService {
@Headers("Accept: application/vnd.tracker.v2+json")
@GET("projects/{projectId}/issues/{issueId}")
suspend fun issue(
@Path("projectId") projectId: String,
@Path("issueId") issueId: Long,
@Header("Accept-Language") locale: String?,
): Issue
@GET("projects/{projectId}/issues")
suspend fun search(
@Path("projectId") projectId: String,
@HeaderMap debugHeaders: Map<String, String>,
): List<IssueSummary>
}go deeper
Recall that @Headers is fixed per method, @Header comes from an argument, and @HeaderMap takes a map of many headers.
Explain that same-named headers are all sent, that null omits an @Header but breaks @HeaderMap, and that Content-Type overrides the body type.
Show where header ownership goes wrong: duplicates between annotations and the client, and tokens threaded through every method.
Set the rule for the codebase: app-wide headers live in the client, endpoint-specific ones on the method, and nothing is declared in both places.
## Three annotations, three jobs Retrofit lets a service method add HTTP headers in three ways. They differ in **where the value comes from**, not in what they put on the wire: | Annotation | Placed on | Value comes from | `null` | |---|---|---|---| | `@Headers` | the method | string literals, each `"Name: Value"` | not applicable | | `@Header("Name")` | a parameter | the argument, via a string converter or `toString()` | header omitted | | `@HeaderMap` | a parameter | a `Map<String, T>` or an `okhttp3.Headers` | `null` map, key or value throws | **`@Headers`** suits values fixed at compile time for one endpoint: a versioned `Accept` media type, a `Cache-Control` hint. Each string must contain a colon with a name before it and a value after it, or parsing fails with `@Headers value must be in the form "Name: Value"`. An empty `@Headers()` is rejected too. **`@Header`** suits values the caller supplies: a locale in `Accept-Language`, a one-off credential for a single endpoint that uses a different scheme. A nullable parameter makes the header optional, and a list or array sends the header once per non-null item. **`@HeaderMap`** suits a variable set of headers chosen at runtime. Support for passing OkHttp's `Headers` type arrived in Retrofit 2.6.0. Unlike `@Header`, it does not tolerate nulls: the request fails with messages such as `Header map contained null value for key 'X-Trace'.` ## How they combine The rule that surprises people: **headers do not overwrite each other**. Both the javadoc and the docs site state that all headers with the same name are included. So: - `@Headers("Accept: application/json")` plus `@Header("Accept") accept: String` sends **two** `Accept` lines. - An `@Header` value that duplicates one added later by an OkHttp interceptor also produces two lines, unless the interceptor replaces it with `header()` rather than `addHeader()`. - `Content-Type` is the exception, described next: the last value Retrofit sees replaces the earlier one. - To make one source win, give the header a single owner. ## The Content-Type exception `Content-Type` is not added as an ordinary header. When `@Headers` or `@Header` names it, Retrofit parses it with `MediaType.get` and uses it to **override the request body's media type**, wrapping the body so the converter's own type is replaced. A malformed value fails with `Malformed content type: ...`. For a method without a body, the value is added as a plain header. ## Non-ASCII values OkHttp's header builder rejects characters outside ASCII, because they are not valid in HTTP header values. Since Retrofit 2.10.0, `@Header`, `@Headers` and `@HeaderMap` have an `allowUnsafeNonAsciiValues` property that lets such values through for servers that expect them. The javadoc calls this not technically compliant with the HTTP specification; use it only when a server requires it. ## When the checks run The two kinds of header annotation are validated at different times. `@Headers` strings are parsed when Retrofit first parses the method, so a missing colon or a malformed `Content-Type` fails on the first call to that method, or inside `create()` when eager validation is on. `@Header` and `@HeaderMap` values only exist at call time, so a `null` map entry or a non-ASCII value fails only when that particular call is made, with an `IllegalArgumentException`. ## Annotation or interceptor? The docs site points the other way for headers that need to be added to **every request**: they can be specified using an OkHttp interceptor. In practice: 1. Put a header on the method when **one endpoint** needs it, or when its value is an argument of that call. 2. Put it in the client when **every call** needs it: authorization, a user agent, an app version. 3. Do not thread an `@Header("Authorization") token: String` parameter through every method; it spreads token handling across call sites and makes refresh harder. How the interceptor is written and where it sits is covered with Retrofit's OkHttp client. ## Worked example In the issue tracker, the single-issue endpoint asks for a richer representation and takes the user's locale: - `@Headers("Accept: application/vnd.tracker.v2+json")` fixes the representation for that method only. - `@Header("Accept-Language") locale: String?` sends the locale when known and nothing when `null`. A search endpoint that forwards arbitrary debug headers chosen in a developer menu takes `@HeaderMap debug: Map<String, String>`, built without null values. ## What interviewers listen for - The **static versus dynamic** split, with `null` omitting a `@Header`. - **No overwriting**: duplicates are all sent. - Knowing that `Content-Type` changes the body's media type. - Sending app-wide headers from the client, not from every method.
- A method has @Headers("Accept: application/json") and a parameter @Header("Accept"). What is sent?Both. Apart from `Content-Type`, Retrofit's header annotations never replace one another, so the request carries two `Accept` lines, one from the method annotation and one from the argument, unless the argument is `null`, which omits it. Give each header a single owner to avoid this.
- What happens when @Header("Content-Type") is set on a method with a @Body?Retrofit parses the value as a `MediaType` and uses it to override the media type of the converted body instead of adding a second header. A value that does not parse fails with `Malformed content type`. On a method without a body, it is added as an ordinary header.
- An @Header("Accept") argument replaces the Accept set by @Headers.
- A null @Header argument sends the header with an empty value.
- @HeaderMap skips null values like @Header does.
- Add the auth token as an @Header parameter on every method.
- Retrofit sends non-ASCII header values by default.
Assumes Retrofit 3.0.0; allowUnsafeNonAsciiValues arrived in 2.10.0 and okhttp3.Headers for @HeaderMap in 2.6.0.