Retrofit 2-URL dinámica


Con Retrofit 2, puede establecer una URL completa en la anotación de un método de servicio como:

public interface APIService {
  @GET("http://api.mysite.com/user/list")
  Call<Users> getUsers();
}

Sin embargo, en mi aplicación, la URL de mis servicios web no se conocen en tiempo de compilación, la aplicación los recupera en un archivo descargado, así que me pregunto cómo puedo usar Retrofit 2 con URL dinámica completa.

Traté de establecer un camino completo como:

public interface APIService {
  @GET("{fullUrl}")
  Call<Users> getUsers(@Path("fullUrl") fullUrl);
}

new Retrofit.Builder()
  .baseUrl("http://api.mysite.com/")
  .build()
  .create(APIService.class)
  .getUsers("http://api.mysite.com/user/list"); // this url should be dynamic
  .execute();

Pero aquí, Retrofit no ve que la ruta es en realidad una URL completa y está tratando de descargar http://api.mysite.com/http%3A%2F%2Fapi.mysite.com%2Fuser%2Flist

Cualquier indicio de cómo podría ¿usar Retrofit con esa url dinámica ?

Gracias

Author: pdegand59, 2015-09-14

4 answers

Creo que lo estás usando de manera equivocada. Aquí hay un extracto de la lista de cambios :

Nuevo: @Url parameter annotation permite pasar una URL completa para un endpoint.

Así que tu interfaz debería ser así:

public interface APIService {
    @GET
    Call<Users> getUsers(@Url String url);
}
 225
Author: Yazazzello,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-07 12:19:02

Quería reemplazar solo una parte de la url, y con esta solución, no tengo que pasar la url completa, solo la parte dinámica:

public interface APIService {

  @GET("users/{user_id}/playlists")
  Call<List<Playlist> getUserPlaylists(@Path(value = "user_id", encoded = true) String userId);
}
 61
Author: Andras Kloczl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-22 23:26:28

Puede usar la bandera codificada en la anotación @Path:

public interface APIService {
  @GET("{fullUrl}")
  Call<Users> getUsers(@Path(value = "fullUrl", encoded = true) String fullUrl);
}
  • Esto evitará la sustitución de / por %2F.
  • No te salvará de que ? sea reemplazado por %3F, sin embargo, por lo que aún no puedes pasar cadenas de consulta dinámicas.
 19
Author: fgysin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-23 17:33:43

A partir de la actualización 2.0.0-beta2, si tiene un servicio que responde a JSON desde esta URL : http://myhost/mypath

Lo siguiente no funciona:

public interface ClientService {
    @GET("")
    Call<List<Client>> getClientList();
}

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("http://myhost/mypath")
    .addConverterFactory(GsonConverterFactory.create())
    .build();

ClientService service = retrofit.create(ClientService.class);

Response<List<Client>> response = service.getClientList().execute();

Pero esto está bien:

public interface ClientService {
    @GET
    Call<List<Client>> getClientList(@Url String anEmptyString);
}

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("http://myhost/mypath")
    .addConverterFactory(GsonConverterFactory.create())
    .build();

ClientService service = retrofit.create(ClientService.class);

Response<List<Client>> response = service.getClientList("").execute();
 14
Author: yann-h,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-03 15:29:55