1
動態變化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();
謝謝,這個問題解決了,但是我對get請求另一個問題,用'intercepter'改造變化後主機試圖獲得由我設置到改造,請看到這個畫面拍攝舊的URL請求http://rupload.ir/upload/lknupff8l09lygr4gnso.png,代碼:'if(host!= null){HttpUrl newUrl = HttpUrl.parse(host); request = request.newBuilder() .url(newUrl) .build(); }' –