2017-08-05 166 views
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(); 

回答

1

基於this github comment,解決的辦法是更換

 HttpUrl newUrl = request.url().newBuilder() 
       .host(host) 
       .build(); 

 HttpUrl newUrl = HttpUrl.parse(host); 
+0

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