使用Retrofit 2,您可以在服务方法的注释中设置完整的URL,如:
public interface APIService {
@GET("http://api.mysite.com/user/list")
Call<Users> getUsers();
}
Run Code Online (Sandbox Code Playgroud)
但是,在我的应用程序中,我的webservices的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();
Run Code Online (Sandbox Code Playgroud)
但在这里,Retrofit并未发现该路径实际上是一个完整的URL并且正在尝试下载 http://api.mysite.com/http%3A%2F%2Fapi.mysite.com%2Fuser%2Flist
有关如何使用这种动态网址进行Retrofit的任何提示吗?
谢谢
我正在尝试使用Dagger 2使用Retrofit 2.0执行登录操作
这是我如何设置Retrofit依赖
@Provides
@Singleton
Retrofit provideRetrofit(Gson gson, OkHttpClient client) {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson)
.client(client)
.baseUrl(application.getUrl())
.build();
return retrofit;
}
Run Code Online (Sandbox Code Playgroud)
这是API接口.
interface LoginAPI {
@GET(relative_path)
Call<Boolean> logMe();
}
Run Code Online (Sandbox Code Playgroud)
我有三个不同的基本网址用户可以登录.因此,在设置Retrofit依赖项时,我无法设置静态URL.我在Application类上创建了一个setUrl()和getUrl()方法.用户登录后,我在调用API调用之前将url设置为Application.
我像这样使用懒惰注射进行改造
Lazy<Retrofit> retrofit
Run Code Online (Sandbox Code Playgroud)
这样,只有当我可以打电话时,Dagger才会注入依赖关系
retrofit.get()
Run Code Online (Sandbox Code Playgroud)
这部分效果很好.我把url设置为改进依赖.但是,当用户键入错误的基本URL(例如,mywifi.domain.com)时,会出现问题,理解它是错误的并更改它(比如mydata.domain.com).由于Dagger已经为改造创建了依赖关系,因此它不会再做了.所以我必须重新打开应用程序并输入正确的URL.
我阅读了不同帖子,使用Dagger在Retrofit上设置动态网址.在我的情况下,没有什么比这更好的了.我想念什么吗?
问题
我需要从USER输入的域调用API,我需要Retrofit在调用之前根据插入的数据编辑我的单例.
有没有办法"重置"我的单身人士,迫使它重新创建?
要么
有没有办法baseUrl在调用之前用我的数据(可能在Interceptor?)更新我的?
码
单身
@Provides
@Singleton
Retrofit provideRetrofit(SharedPreferences prefs) {
String apiUrl = "https://%1s%2s";
apiUrl = String.format(apiUrl, prefs.getString(ACCOUNT_SUBDOMAIN, null), prefs.getString(ACCOUNT_DOMAIN, null));
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(new HeaderInterceptor())
.build();
return new Retrofit.Builder()
.baseUrl(apiUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
}
@Provides
@Singleton
API provideAPI(Retrofit retrofit) {
return retrofit.create(API.class);
}
Run Code Online (Sandbox Code Playgroud)
API
@FormUrlEncoded
@POST("endpoint")
Observable<Response> logIn(@Field("login") String login, @Field("password") String password);
Run Code Online (Sandbox Code Playgroud)
它现在如何运作
好的想法是SharedPrefs在API调用之前保存用户域数据并baseUrl使用格式化的String进行修改.