使用匕首2
问题描述:
动态变化URL的Android实现HostSelectionInterceptor我只了解我怎么能实现Retrofit
与Dagger2设置动态变更网址这个reference使用匕首2
我尽量让单模与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: unexpected host: http://myUrl.com/ at okhttp3.HttpUrl$Builder.host(HttpUrl.java:754)
问题是由setHost
方法在这行代码设置的主机:
HttpUrl newUrl = request.url().newBuilder()
.host(host)
.build();
答
基于this github comment,解决的办法是更换
HttpUrl newUrl = request.url().newBuilder()
.host(host)
.build();
与
HttpUrl newUrl = HttpUrl.parse(host);
谢谢,这个问题解决了,但是我对get请求另一个问题,用'intercepter'改造变化后主机试图获得由我设置到改造,请看到这个画面拍摄旧的URL请求http://rupload.ir/upload/lknupff8l09lygr4gnso.png,代码:'if(host!= null){HttpUrl newUrl = HttpUrl.parse(host); request = request.newBuilder() .url(newUrl) .build(); }' –