skip to content

In Retrofit, how do you call a URL the server returns at runtime, such as a pre-signed download link, and what constraints does @Url carry?

level: middleimportance: should knowfreq 45%

answer

  1. empty method annotation path
  2. parameter replaces the template
  3. resolved like a link
  4. no path blocks allowed
  5. same client, same interceptors

basics

~20 s

Declare the method annotation with no path and pass the URL as an @Url parameter. Retrofit resolves it against the baseUrl like a link, so an absolute URL replaces the host. @Url cannot be combined with @Path or a path in the annotation.

solid answer

~40 s

For a URL the server hands back, such as a pre-signed attachment link or a `next` page link, write `@GET suspend fun download(@Url url: String): ResponseBody` with no path in `@GET`. The value is resolved against the `baseUrl` the same way an endpoint path is: an absolute URL replaces scheme and host, a relative one is resolved under the base. The parameter may be a `String`, OkHttp's `HttpUrl`, `java.net.URI` or `android.net.Uri`. Retrofit rejects a method that also has a path in its annotation, a `@Path` parameter, a second `@Url`, or a `@Url` declared after a `@Query`, `@QueryName` or `@QueryMap`; a `null` argument throws. The request still runs through the same OkHttp client, so an interceptor that adds a bearer token would send it to the storage host too.

code

kotlin · 11 lines
kotlin
interface AttachmentService {
    @GET("projects/{projectId}/issues/{issueId}/attachments/{attachmentId}")
    suspend fun attachment(
        @Path("projectId") projectId: String,
        @Path("issueId") issueId: Long,
        @Path("attachmentId") attachmentId: String,
    ): AttachmentInfo

    @GET
    suspend fun download(@Url downloadUrl: String): ResponseBody
}

go deeper

for a junior

Recall that a URL known only at runtime is passed with @Url and the method annotation has no path of its own.

for a middle

Explain how the value resolves against the baseUrl, which parameter types are allowed, and which combinations Retrofit rejects.

for a senior

Spot the production risks: a bearer token added to a third-party host, a relative link losing the API prefix, and signed queries altered by extra @Query values.

for a principal

Decide how the app treats server-issued links: followed verbatim with @Url, never rebuilt, and fetched through a client that sends credentials only to the API's own host.

## The problem @Url solves A service interface usually fixes every endpoint at compile time: `@GET("projects/{projectId}/issues")`. Some URLs only exist at runtime because the server hands them out: - a **pre-signed download link** for an issue attachment, valid for a limited time and hosted on a storage domain; - a **pagination link** such as `next` in a list response; - a link embedded in a resource that the client is meant to follow as given. Rebuilding these URLs from parts would duplicate the server's logic and, for a signed link, break the signature. Retrofit's `@Url` takes the whole URL as an argument instead. ## Declaring it The HTTP method annotation is written **without a path**, and one parameter carries `@Url`: - `@GET suspend fun download(@Url url: String): ResponseBody` - `@GET suspend fun page(@Url next: String): IssuePage` The value replaces the relative URL that the annotation would normally supply. Retrofit then resolves it against the `baseUrl` with OkHttp's `HttpUrl.resolve`, exactly as it resolves annotation paths: | `@Url` value | Base `https://tracker.example.com/api/v2/` gives | |---|---| | `https://files.example.com/a/b?sig=...` | `https://files.example.com/a/b?sig=...` | | `issues?page=3` | `https://tracker.example.com/api/v2/issues?page=3` | | `/issues?page=3` | `https://tracker.example.com/issues?page=3` | | `//files.example.com/a/b` | `https://files.example.com/a/b` | Retrofit does not apply `@Path`-style encoding to the value; it passes the string to URL resolution as it is. ## Rules Retrofit enforces When Retrofit parses the method it throws `IllegalArgumentException` for each of these: 1. A path in the method annotation as well: `@Url cannot be used with @GET URL`. The annotation must be bare. 2. A `@Path` parameter on the same method: `@Path parameters may not be used with @Url.` There is no template to fill. 3. Two `@Url` parameters: `Multiple @Url method annotations found.` 4. A `@Url` declared after a `@Query`, `@QueryName` or `@QueryMap` parameter. The `create()` javadoc says to annotate the **first** parameter; the parser's actual rule is only that no query parameter comes before it. 5. A parameter type other than `okhttp3.HttpUrl`, `String`, `java.net.URI` or `android.net.Uri`. 6. A method annotation with no path and no `@Url` at all: `Missing either @GET URL or @Url parameter.` At call time, a `null` argument throws `@Url parameter is null.` `@Query` parameters after the `@Url` are allowed and are appended to the resolved URL. For a pre-signed link that is usually a mistake, because changing the query may invalidate the signature. ## What goes wrong in production - **Credentials sent to another host.** The call runs through the same `OkHttpClient` as every other Retrofit call, so an interceptor that adds the app's bearer token adds it to the storage host's request as well. Such a request may be rejected, and the token leaks to a third party. How the client decides which requests get the token is covered with Retrofit's OkHttp client; the point here is that `@Url` does not change which interceptors run. - **A relative link resolved against the wrong base.** A server that returns `/issues?page=3` drops the base's `/api/v2/` prefix, by the same rule as a leading slash in an annotation. - **Large downloads buffered in memory.** A `ResponseBody` return type is read into memory unless the method is marked for streaming; streaming downloads have their own lesson. ## Choosing @Url over other options | Need | Declaration | |---|---| | A fixed endpoint with variable ids | `@GET("issues/{issueId}")` with `@Path` | | A fixed endpoint with variable filters | `@GET("issues")` with `@Query` | | A link the server returns, used as given | bare `@GET` with `@Url` | | A different environment for the whole client | a new `Retrofit` built with another `baseUrl` | `@Url` is the only one of these that lets the server choose the host and path for a single call. It does not replace a base URL for a whole client, and it should not be used to assemble a path from fragments that `@Path` could fill. ## Worked example The attachment endpoint returns JSON with a `downloadUrl` that points at `files.example.com` and carries a signature in its query. The app passes that string unchanged to `download(@Url url: String)`, adds no `@Query`, and lets the storage host see only what the link itself authorises. A list screen takes the `next` link from each page and calls `page(@Url next)` until it is absent. ## What interviewers listen for - A bare method annotation plus `@Url`, rather than string-building a path into `@Path`. - The **resolution rules**: absolute replaces host, leading slash keeps only the host, relative goes under the base. - The incompatibilities with `@Path` and with an annotation path. - Awareness that the shared client's headers travel with the request.

  • Can a Retrofit @Url point at a different host than the baseUrl?
    Yes. A full URL with a scheme and host replaces both when it is resolved against the base, and a `//host/path` value replaces the host while keeping the base's scheme. The request still uses the same OkHttp client, so its interceptors and settings apply to the other host too.
  • Why does Retrofit reject a @Url declared after a @Query parameter?
    When Retrofit appends the first query pair it combines the relative URL with the base URL, so a URL arriving afterwards would be ignored. The parser therefore throws `IllegalArgumentException` saying a `@Url` parameter must not come after a `@Query`; declaring `@Url` first, with queries after it, works.

  • @Url is combined with a path in @GET to add a prefix.
  • A full URL passed to @Url is appended to the baseUrl path.
  • Requests made through @Url skip the client's interceptors.
  • @Path can fill blocks inside a URL passed with @Url.
  • Retrofit percent-encodes the @Url value like a @Path value.