2017-10-16 47 views
0

我正在创建一个新的MVP项目,并使用Dagger 2与改造,但我面临的问题是应用程序应该从服务器获取基本URL并开始调用网络API 。Dagger 2更新基地URL在改造

这里的问题是我无法在运行时更新URL! 我想出的最佳解决方案是更新URL,但在应用程序的下一次运行中!

我尝试了很多想法和解决方案存在StackOverFlow但他们都没有工作!

private final Application mApplication; 
private String mBaseUrl; 


public ApplicationModule(Application application, String baseUrl) { 
    mApplication = application; 
    mBaseUrl = baseUrl; 
} 


@Provides 
@Singleton 
OkHttpClient providesOkHttpClient() { 
    OkHttpClient.Builder client = new OkHttpClient.Builder(); 

    client.readTimeout(Constants.TIMEOUT, TimeUnit.SECONDS); 
    client.connectTimeout(Constants.TIMEOUT, TimeUnit.SECONDS); 

    return client.build(); 
} 


@Provides 
@RetrofitGSON 
Retrofit providesRetrofit(OkHttpClient okHttpClient) { 
    return new Retrofit.Builder() 
      .baseUrl(mBaseUrl) 
      .addConverterFactory(ScalarsConverterFactory.create()) 
      .addConverterFactory(GsonConverterFactory.create(new GsonBuilder() 
          .setPrettyPrinting() 
          .create() 
        ) 
      ) 
      .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) 
      .client(okHttpClient) 
      .build(); 
} 

任何帮助将非常感激!

回答

0

对于所有遇到此类问题的人,下面是如何解决这个问题。 你需要重写okhttp拦截器。

@Singleton 
public class ExampleInterceptor implements Interceptor { 
    private static ExampleInterceptor sInterceptor; 
    private String mScheme; 
    private String mHost; 

    @Inject 
    public static ExampleInterceptor get() { 
     if (sInterceptor == null) { 
      sInterceptor = new ExampleInterceptor(); 
     } 
     return sInterceptor; 
    } 

    private ExampleInterceptor() { 
     // Intentionally blank 
    } 

    public void setInterceptor(String url) { 
     HttpUrl httpUrl = HttpUrl.parse(url); 
     mScheme = httpUrl.scheme(); 
     mHost = httpUrl.host(); 
    } 

    @Override 
    public Response intercept(Chain chain) throws IOException { 
     Request original = chain.request(); 

     // If new Base URL is properly formatted than replace with old one 
     if (mScheme != null && mHost != null) { 
      HttpUrl newUrl = original.url().newBuilder() 
       .scheme(mScheme) 
       .host(mHost) 
       .build(); 
     original = original.newBuilder() 
       .url(newUrl) 
       .build(); 
     } 
    return chain.proceed(original); 
    } 
}