Search code examples
androidretrofit2

Using @Path and @Url paramers together with retrofit2


I'm using retrofit2 to comunicate with a webapi. I need to set the URL of the webapi dynamically beacuase the user can change it, so i use the @Url annotation to specify it like this:

@POST
Call<LoginResponse> login(@Url String url, @Body LoginRequest user);

In one of the operations, i need to send some path parameters to the server, so i do this:

@GET
Call<DataResponse> getOrder(@Url String url,
                             @Header(WEBAPI_EMAIL_HEDER) String email,
                             @Header(WEBAPI_TOKEN_ID_HEDER) String token,
                             @Path("id") int id);

When i call the operation getOrder(...), an exception is rised by retrofit because i am not suppoused to use @Url and @Path parameters in the same operation.

This is the exception:

java.lang.IllegalArgumentException: @Path parameters may not be used with @Url. (parameter #4)

One solution is to replace the id parameter on the url and use only the @Url parameter in the invokation. But i think this is not the best way, beacuase i will be doing this with all the operations with @Path parameters.

Is there any other cleaner solution? Maybe using another retrofit2 annotation?

Thanks in advance.


Solution

  • As described in the post Retrofit 2 - Dynamic URL, the @Url notation assumes that the String is a fully defined URL and does not check whether it contains @Path variables.

    To use the @Path annotation, you have to configure an endpoint URL and include the @Path variable inside the @GET() annotation.