Retrofit URL manipulation

How we can manage and change the URL of a request in Retrofit

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

Download the starter project here

Github repository

Url manipulation refers to different ways to modify the url that the request will be calling. So that means that we can pass the URL as a parameter, make it static etc.

In this article we will look at the different options that we have when we are building our URL.

Static URL

The first option is a static URL. We have a BASE_URL and an endpoint that the system appends to the end of the BASE_URL to retrieve the whole URL to call.

The structure is the one we’re built so far in our series.

@GET(“apiCall”)

fun callGet(): Call<ApiCallResponse>

Bypass the Base url

Another way of making a URL static is to bypass the base url completely. You have the option to put the whole URL in the get request and Retrofit will simply take that URL and call it.

@GET(“https://example.com/user/info”)

fun callUrlBypass(): Call<ApiCallResponse>

Dynamic URL

We can also pass the complete URL inside one of the parameters of the calling function and that will make Retrofit call the url that we pass dynamically. To do that we use the @Url annotation.

@GET

fun callUrlDynamic(@Url url: String): Call<ApiCallResponse>

Replacement blocks

In this case we work with BASE_URL and we have an endpoint defined in the function. The endpoint definition includes paths that are surrounded by curly brackets, which will be replaced at runtime with the parameters that are provided. In our example, we replace the paths ‘user’ and ‘end’ with proper endpoints. In the function, we specify the values that need to be replaced with the @Path annotation that takes the name of the path as a parameter.

@GET(“account/{user}/{end}”)

fun callUrlPath(@Path(“user”) u: String, @Path(“end”) e: String): Call<ApiCallResponse>

We can also have a single path element that is replaced at run time

@GET(“{info}”)

fun callUrlPath(@Path(“info”) info: String): Call<ApiCallResponse>

If we update the ApiCallService class we should have a functioning app

fun call(context: Context) =

    getApi(context).callUrlPath(“apiCall”)

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

Close Bitnami banner
Bitnami