Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class ApiManager(private val context: Context) {
- val CURRENT_SERVER_ADDRESS: String = BuildConfig.SERVER_ADDRESS
- lateinit var apiService: ApiService
- companion object {
- lateinit var httpClient: OkHttpClient
- }
- init {
- val retrofit = initRetrofit()
- initServices(retrofit)
- }
- private fun initRetrofit(): Retrofit {
- val loggingInterceptor = HttpLoggingInterceptor().apply {
- level = HttpLoggingInterceptor.Level.BODY
- }
- val cookieManager = CookieManager()
- cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL)
- val cacheSize = 10 * 1024 * 1024L // 10 MB
- val cache = Cache(context.cacheDir, cacheSize)
- httpClient = OkHttpClient.Builder()
- .readTimeout(45, TimeUnit.SECONDS)
- .writeTimeout(45, TimeUnit.SECONDS)
- .cookieJar(JavaNetCookieJar(cookieManager))
- .addInterceptor(loggingInterceptor)
- .addInterceptor({ chain ->
- try {
- chain.proceed(chain.request())
- } catch (e: Exception) {
- val offlineRequest = chain.request().newBuilder()
- .header(
- "Cache-Control", "public, only-if-cached," +
- "max-stale=" + 60 * 60
- )
- .build()
- chain.proceed(offlineRequest)
- }
- })
- .cache(cache)
- .build()
- return Retrofit.Builder()
- .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
- .addConverterFactory(GsonConverterFactory.create())
- .client(httpClient)
- .baseUrl(CURRENT_SERVER_ADDRESS)
- .build()
- }
- private fun initServices(retrofit: Retrofit) {
- apiService = retrofit.create(ApiService::class.java)
- }
- fun toRequestBody(value: String): RequestBody {
- return RequestBody.create(MediaType.parse("text/plain"), value)
- }
- }
Add Comment
Please, Sign In to add comment