@InstallIn(SingletonComponent::class)
@Module
class NetworkModule {
@Singleton
@Provides
fun providesRetrofit(okHttpClient: OkHttpClient): Retrofit{
//val contentType = "application/json".toMediaType()
val interceptor = HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.BODY
val httpBuilder = OkHttpClient.Builder()
httpBuilder
//.dispatcher(dispatcher)
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.addInterceptor(interceptor) /// show all JSON in logCat
val mClient = httpBuilder.build()
return Retrofit.Builder()
//.addConverterFactory(Json.asConverterFactory(contentType))
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(BASE_URL)
.client(mClient)
.build()
}
@Provides
fun provideHTTPLoggingInterceptor(): HttpLoggingInterceptor {
val interceptor = HttpLoggingInterceptor()
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
return interceptor
}
@Provides
fun provideOkHttpClient(loggingInterceptor: HttpLoggingInterceptor
): OkHttpClient {
return OkHttpClient.Builder()
.callTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60,TimeUnit.SECONDS)
.writeTimeout(60,TimeUnit.SECONDS)
.addInterceptor(loggingInterceptor)
.build()
}
@Singleton
@Provides
fun providesSalesAPI(retrofit: Retrofit): SalesApi {
return retrofit.create(SalesApi::class.java)
}
}
如何在单击任何按钮时更改BASE_URL?我使用MVVM存储库模式,无法更改URL运行时。请帮助我在上面的例子中有什么要改变的。注意:如果我重新启动应用程序的URL将更改,但我想改变没有应用程序重新启动的URL
2条答案
按热度按时间qxgroojn1#
我不确定这是否是最好的解决方案,但您可以使用两个
BASE_URL
创建两个Retrofit
示例:ars1skjm2#
请按此https://medium.com/nerd-for-tech/change-retrofit-base-url-on-runtime-2036ef1dee44
截击机会帮你的