这是我的单身人士课程。
public class GetRetrofit {
static volatile Retrofit retrofit = null;
public static Retrofit getInstance() {
if (retrofit == null) {
synchronized (GetRetrofit.class) {
if (retrofit == null) {
OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
builder.readTimeout(30, TimeUnit.SECONDS);
builder.connectTimeout(30, TimeUnit.SECONDS);
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
builder.addInterceptor(interceptor);
// builder.addInterceptor(new UnauthorisedInterceptor(context));
OkHttpClient client = builder.build();
retrofit =
new Retrofit.Builder().baseUrl("DYNAMIC_URL")
.client(client).addConverterFactory(GsonConverterFactory.create()).build();
//addConverterFactory(SimpleXmlConverterFactory.create())
}
}
}
return retrofit;
}
}
我想更改动态基本网址。
例如:http://192.168.1.60:8888/property/Apiv1需要在运行时http://192.168.1.50:8008/inventory/Apiv1更改此网址。
如何在运行时动态更改这两个url。请帮帮我。
答案 0 :(得分:1)
以下代码将显示一种在运行时更改改装基本URL的方法,但代价是略微破坏单例模式。该模式仍然部分适用。我稍后会解释。
检查GetRetrofit
的此修改版本。
public class GetRetrofit {
static volatile Retrofit retrofit = null;
private static String baseUrlString = "http://192.168.1.60:8888/property/Apiv1";
public static void updateBaseUrl(String url){
baseUrlString = url;
retrofit = getRetrofitObj();
}
public static Retrofit getInstance() {
if (retrofit == null) {
synchronized (GetRetrofit.class ) {
if (retrofit == null) {
retrofit = getRetrofitObj();
}
}
}
return retrofit;
}
public static Retrofit getRetrofitObj() {
OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
builder.readTimeout(30, TimeUnit.SECONDS);
builder.connectTimeout(30, TimeUnit.SECONDS);
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
builder.addInterceptor(interceptor);
// builder.addInterceptor(new UnauthorisedInterceptor(context));
OkHttpClient client = builder.build();
retrofit = new Retrofit.Builder().baseUrl(baseUrlString)
.client(client).addConverterFactory(GsonConverterFactory.create()).build();
}
}
因此,GetRetrofit
有baseUrlString
初始化/保存我们的动态网址。如果您不需要更新默认的基本网址,那么您可以打电话,
Retrofit retrofit = GetRetrofit.getInstance();
但是当我们需要将默认网址更改为其他内容(例如http://192.168.1.50:8008/inventory/Apiv1
)时,我们需要先更新我们的基本网址。
GetRetrofit.updateBaseUrl("http://192.168.1.50:8008/inventory/Apiv1");
Retrofit retrofit = GetRetrofit.getInstance(); // this provides new retrofit instance with given url
仅当您更新网址时,才会根据此新网址构建新的retrofit
实例。只要您不需要更新基本网址,只需调用即可获得单例改造实例,
Retrofit retrofit = GetRetrofit.getInstance();
所以在某种程度上它部分地保留了单身模式的特征。
希望这有帮助。