【发布时间】:2017-08-18 08:02:53
【问题描述】:
我正在为我的应用程序使用改造和 Dagger2。我想根据用户在 Spinner 中选择的内容动态更改应用程序的 baseUrl。
在互联网上花了几个小时后,我得出结论,可以动态更改 baseUrl。
依赖注入看起来像这样:
APiModule
@Module
public class ApiModule {
String mBaseUrl;
public ApiModule(String mBaseUrl) {
this.mBaseUrl = mBaseUrl;
}
@Provides
@Singleton
OkHttpClient provideOkhttpClient(Cache cache) {
OkHttpClient.Builder client = new OkHttpClient.Builder();
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// set your desired log level
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
client.addInterceptor(logging);
client.cache(cache);
return client.build();
}
@Provides
@Singleton
Retrofit provideRetrofit(OkHttpClient okHttpClient) {
return new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(mBaseUrl)
.client(okHttpClient)
.build();
}
}
我根据来自互联网的参考创建了一个额外的类
HostSelectionInterceptor.java
import java.io.IOException;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
/** An interceptor that allows runtime changes to the URL hostname. */
@Module(includes = {ApiModule.class})
public final class HostSelectionInterceptor implements Interceptor {
private volatile String host;
@Provides
@Singleton
public String setHost(String host) {
this.host = host;
return this.host;
}
public String getHost() {
return host;
}
@Provides
@Singleton
@Override
public okhttp3.Response intercept(Chain chain) {
Request request = chain.request();
String host = getHost();
if (host != null) {
/* HttpUrl newUrl = request.url().newBuilder()
.host(host)
.build();*/
HttpUrl newUrl = HttpUrl.parse(host);
request = request.newBuilder()
.url(newUrl)
.build();
}
try {
return chain.proceed(request);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
现在,我的问题是如何在更改 Spinner 时使用 HostSelectionInterceptor 更改我的 baseUrl。
【问题讨论】:
标签: java android retrofit2 dagger-2