您可以通过创建改造对象工厂方法的重载方法来做到这一点。大概是这个样子。
public class RestClient {
public static final int DEFAULT_TIMEOUT = 20;
public static <S> S createService(Class<S> serviceClass) {
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
OkHttpClient client = httpClient.build();
okHttpClient.setReadTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
okHttpClient.setConnectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL)
.client(client)
.build();
return retrofit.create(serviceClass);
}
public static <S> S createService(Class<S> serviceClass, int timeout) {
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
OkHttpClient client = httpClient.build();
okHttpClient.setReadTimeout(timeout, TimeUnit.SECONDS);
okHttpClient.setConnectTimeout(timeout, TimeUnit.SECONDS);
Retrofit retrofit = new Retrofit.Builder().baseUrl(APIConfig.BASE_URL)
.client(client)
.build();
return retrofit.create(serviceClass);
}
}
如果你想用默认的 timout 调用 api,你可以这样称呼它。
MyAPI api = RestClient.createService(MyAPI.class);
api.notImportant();
如果您想通过身份验证调用 api,请使用第二个:
int timeout = 35;
MyAPI api2 = RestClient.createService(MYAPI.class, timeout);
api2.veryImportant();
另一种解决方案是使用不同的 OkHttpClient 配置创建不同的方法,而不是创建重载方法。希望此解决方案可以解决您的问题。