skip to content

With Retrofit, when do you send @FormUrlEncoded with @Field or @FieldMap instead of a @Body, and which combinations does Retrofit reject?

level: middleimportance: should knowfreq 45%

answer

  1. what the server parses
  2. method-level switch
  3. one encoding per method
  4. no body alongside fields

basics

~20 s

Use @FormUrlEncoded when the server expects application/x-www-form-urlencoded key=value pairs. @Field adds one pair, skipping null; @FieldMap adds many and rejects null. Retrofit refuses @Field without @FormUrlEncoded, @Body beside fields, and form encoding on a bodiless method.

solid answer

~40 s

`@FormUrlEncoded` on the method switches the body to `application/x-www-form-urlencoded`. Each `@Field("name")` parameter adds one pair, form-encoded so a space becomes `+`; a `null` value is skipped and a `List` repeats the name. `@FieldMap` adds a map of pairs and rejects a `null` map, key or value. The values go through a string converter, not the body converter, so no JSON library is involved. Retrofit validates the shape: `@Field` without `@FormUrlEncoded` fails, a method with `@FormUrlEncoded` but no `@Field` fails, `@Body` cannot sit beside fields, `@FormUrlEncoded` with `@Multipart` is rejected, and form encoding on `@GET` fails because that method has no body. Choose it when the endpoint parses form data, not when it expects JSON.

code

kotlin · 10 lines
kotlin
interface IssueCommentService {
    @FormUrlEncoded
    @POST("projects/{projectId}/issues/{issueId}/comments")
    suspend fun addComment(
        @Path("projectId") projectId: String,
        @Path("issueId") issueId: Long,
        @Field("body") body: String,
        @Field("visibility") visibility: String?,
    ): Unit
}

go deeper

for a junior

Recall that @FormUrlEncoded on the method plus @Field on parameters sends key=value pairs as a form body.

for a middle

Explain null handling for @Field versus @FieldMap, list expansion, and each declaration Retrofit rejects at parse time.

for a senior

Choose form encoding from the server's contract, and diagnose a rejected method from its IllegalArgumentException message.

for a principal

Keep a clear rule for mixed APIs: form endpoints declared with fields, JSON endpoints with a body, files with multipart, and nothing improvised in between.

## What form encoding is An HTML form submitted with the default settings sends its fields as a request body of type `application/x-www-form-urlencoded`: `name=value` pairs joined with `&`, each name and value percent-encoded and spaces written as `+`. Many endpoints still accept or require this format, for example older endpoints of a service and endpoints that a web form posts to as well. When a server parses a form, sending JSON with `@Body` fails even though the data is the same. Retrofit builds such a body from annotations, without a converter for the body itself. ## The annotations - **`@FormUrlEncoded`** on the method: the request body becomes form-encoded and gets the `application/x-www-form-urlencoded` content type. - **`@Field("name")`** on a parameter: one pair. The value is converted with a string converter (or `toString()`) and form-encoded. A `null` value is **skipped**; a `List` or array produces one pair per non-null item. - **`@FieldMap`** on a `Map<String, T>` parameter: one pair per entry. A `null` map, key or value is **not allowed** and throws `IllegalArgumentException`, mirroring `@QueryMap`. - **`encoded = true`** on either annotation tells Retrofit the value is already encoded, so it is not encoded again. ## What Retrofit rejects, and when Retrofit checks a method's annotations when it first parses that method and throws `IllegalArgumentException` with the method name in the message: | Declaration | Message | |---|---| | `@Field` on a method without `@FormUrlEncoded` | `@Field parameters can only be used with form encoding.` | | `@FormUrlEncoded` with no `@Field` parameter | `Form-encoded method must contain at least one @Field.` | | `@FormUrlEncoded` together with a `@Body` parameter | `@Body parameters cannot be used with form or multi-part encoding.` | | `@FormUrlEncoded` together with `@Multipart` | `Only one encoding annotation is allowed.` | | `@FormUrlEncoded` on `@GET`, `@DELETE`, `@HEAD` or `@OPTIONS` | `FormUrlEncoded can only be specified on HTTP methods with request body (e.g., @POST).` | The last row follows from how Retrofit models methods: `@POST`, `@PUT` and `@PATCH` carry a body, the others do not. `@HTTP(method = "DELETE", path = "...", hasBody = true)` is the escape hatch when a server wants a body on a method that Retrofit treats as bodiless. ## How the body is built Retrofit does not hand form fields to a converter. For a form-encoded method it keeps an OkHttp `FormBody.Builder` and, as each parameter is applied in declaration order, adds one pair per non-null `@Field` value or `@FieldMap` entry. When the request is assembled, the finished `FormBody` becomes the request body and carries its own content type. The consequences are practical: - the order of pairs in the body follows the order of parameters, then list order, then map iteration order; - a value type with a custom string form, such as an enum whose wire name differs from its Kotlin name, needs a string converter registered on the builder, or its `toString()` is sent; - the request is small and fully built before it is sent, which suits short forms rather than large payloads. ## Choosing between form fields and a body 1. **Read the server's contract.** If it documents form parameters, use `@FormUrlEncoded`; if it documents a JSON payload, use `@Body` with a converter. 2. **Use `@Field` for a fixed set of named values**, with nullable parameters for optional ones, since nulls vanish. 3. **Use `@FieldMap` only for a genuinely variable set**, and build the map without nulls. 4. **Keep file uploads out of it.** Files and mixed binary parts use multipart encoding, which has its own annotations and its own lesson. A `@Query` on the same method still works; it goes to the URL, not the form body. ## Worked example The issue tracker has a legacy endpoint that a web page also posts to: it adds a comment to an issue from form fields. The service method in the example below sends: ``` POST projects/ANDROID/issues/42/comments Content-Type: application/x-www-form-urlencoded body=Crash+on+rotate&visibility=internal ``` Passing `visibility = null` drops that pair, and the server applies its default. Adding a `@Body` parameter to the same method would make Retrofit reject the method rather than send two bodies. ## What a good answer shows - It starts from **what the server parses**, not from which annotation is shorter. - It knows `@Field` **skips null** while `@FieldMap` **rejects** it. - It can name at least two shapes Retrofit refuses: `@Field` without the method annotation, and `@Body` beside fields. - It knows field values use a **string converter**, so no JSON converter is needed for this request.

  • Do you need a converter factory for a Retrofit @FormUrlEncoded request?
    Not for the request body. Each `@Field` value is turned into a string by a string converter, which defaults to `toString()`, and Retrofit builds the form body itself. A converter is still needed if the response is decoded into an object.
  • Why does adding @FormUrlEncoded to a @GET method fail?
    Retrofit treats `@GET` as a method without a request body, and form encoding describes a body. It throws `IllegalArgumentException` saying FormUrlEncoded can only be specified on methods with a request body. For a GET, the values belong in `@Query` parameters.

  • @Field works on any method without @FormUrlEncoded.
  • @FieldMap silently skips entries whose value is null.
  • A @Body and @Field parameters can be combined in one request.
  • Form fields go through the JSON converter like a @Body.
  • @FormUrlEncoded on a @GET puts the fields in the query string.