【发布时间】:2017-08-05 08:25:13
【问题描述】:
我刚刚了解如何使用 Dagger2 实现 Retrofit 以在此 reference 上设置动态更改 url
我尝试使用 HostSelectionInterceptor 类制作简单的模块以在 Dagger2 上使用它,但我无法正确制作,并且出现错误:
我的NetworkModule:
@Module(includes = ContextModule.class)
public class NetworkModule {
@Provides
@AlachiqApplicationScope
public HttpLoggingInterceptor loggingInterceptor() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
Timber.e(message);
}
});
interceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
return interceptor;
}
...
@Provides
@AlachiqApplicationScope
public HostSelectionInterceptor hostSelectionInterceptor() {
return new HostSelectionInterceptor();
}
@Provides
@AlachiqApplicationScope
public OkHttpClient okHttpClient(HostSelectionInterceptor hostInterceptor, HttpLoggingInterceptor loggingInterceptor, Cache cache) {
return new OkHttpClient.Builder()
.addInterceptor(hostInterceptor)
.addInterceptor(loggingInterceptor)
.connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.cache(cache)
.build();
}
}
和HostSelectionInterceptor 模块:
@Module(includes = {NetworkModule.class})
public final class HostSelectionInterceptor implements Interceptor {
private volatile String host;
@Provides
@AlachiqApplicationScope
public String setHost(String host) {
this.host = host;
return this.host;
}
public String getHost() {
return host;
}
@Provides
@AlachiqApplicationScope
@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();
request = request.newBuilder()
.url(newUrl)
.build();
}
try {
return chain.proceed(request);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
我现在收到此错误:
java.lang.IllegalArgumentException:意外主机:http://myUrl.com/ okhttp3.HttpUrl$Builder.host(HttpUrl.java:754)
问题是在这行代码通过setHost方法设置主机:
HttpUrl newUrl = request.url().newBuilder()
.host(host)
.build();
【问题讨论】:
标签: android retrofit retrofit2 dagger-2 dagger