使用Retrofit 2,您可以在服务方法的注释中设置完整的URL,如下所示:
public interface APIService {
@GET("http://api.mysite.com/user/list")
Call<Users> getUsers();
}
然而,在我的应用程序中,我的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();
但是在这里,Retrofit并没有看到这个路径实际上是一个完整的URL,而是试图下载http://api.mysite.com/http%3A%2F%2Fapi.mysite.com%2Fuser%2Flist
任何提示,我可以使用这样的动态url改造?
谢谢你!
步骤1
Please define a method in Api interface like:-
@FormUrlEncoded
@POST()
Call<RootLoginModel> getForgotPassword(
@Url String apiname,
@Field(ParameterConstants.email_id) String username
);
步骤2
对于最佳实践,定义一个用于改造实例的类:-
public class ApiRequest {
static Retrofit retrofit = null;
public static Retrofit getClient() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
.addInterceptor(logging)
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.build();
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(URLConstants.base_url)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
步骤3
在活动中定义:-
final APIService request =ApiRequest.getClient().create(APIService.class);
Call<RootLoginModel> call = request.getForgotPassword("dynamic api
name",strEmailid);
从Retrofit 2.0.0-beta2开始,如果你有一个服务从这个URL响应JSON:
http://myhost/mypath
以下是无效的:
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();
但这是可以的:
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();