我正在使用翻新& Dagger2用于我的应用程序。我想基于用户在Spinner中选择的内容动态更改应用程序的baseUrl。使用翻新和匕首动态更改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;
}
}
现在,我的问题是我如何使用HostSelectionInterceptor更改我的baseUrl更改微调。
的可能的复制[匕首+改造动态URL](https://stackoverflow.com/questions/36769923/dagger-retrofit-dynamic-url) –