猿问

改造2-动态网址

使用Retrofit 2,您可以在服务方法的注释中设置完整的URL,例如:


public interface APIService {

  @GET("http://api.mysite.com/user/list")

  Call<Users> getUsers();

}

但是,在我的应用程序中,我的Web服务的URL在编译时未知,该应用程序在下载的文件中检索它们,因此我想知道如何将Retrofit 2与完整的动态URL结合使用。


我试图设置一个完整的路径,如:


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();

但是在这里,Retrofit并未看到该路径实际上是完整的URL,而是试图下载 http://api.mysite.com/http%3A%2F%2Fapi.mysite.com%2Fuser%2Flist


关于如何将Retrofit与此类动态url一起使用的任何提示?


谢谢


斯蒂芬大帝
浏览 326回答 3
3回答

白猪掌柜的

我认为您使用的方式有误。这是变更日志的摘录:新增:@Url参数注释允许为端点传递完整的URL。因此,您的界面应如下所示:public interface APIService {&nbsp; &nbsp; @GET&nbsp; &nbsp; Call<Users> getUsers(@Url String url);}

慕婉清6462132

我只想替换一部分URL,使用此解决方案,我不必传递整个URL,而只需传递动态部分:public interface APIService {&nbsp; @GET("users/{user_id}/playlists")&nbsp; Call<List<Playlist> getUserPlaylists(@Path(value = "user_id", encoded = true) String userId);}

慕的地8271018

您可以在注释上使用编码标志@Path:public interface APIService {&nbsp; @GET("{fullUrl}")&nbsp; Call<Users> getUsers(@Path(value = "fullUrl", encoded = true) String fullUrl);}这将防止更换/用%2F。但是,它不会使您免于?被替换%3F,因此您仍然无法传递动态查询字符串。
随时随地看视频慕课网APP

相关分类

Android
我要回答