Dagger 2在Retrofit中更新基本URL

时间:2017-10-16 05:46:32

标签: android retrofit dagger-2

我正在创建一个新的MVP项目,并使用Dagger 2和Retrofit,但我正面临这个问题,即app应该从服务器获取基本URL并开始调用网络API。

这里的问题是我无法在运行时更新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();
}

任何帮助都会非常感激!

1 个答案:

答案 0 :(得分: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);
    }
}