Guest User

Untitled

a guest
Feb 25th, 2018
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 2.07 KB | None | 0 0
  1. class ApiManager(private val context: Context) {
  2.     val CURRENT_SERVER_ADDRESS: String = BuildConfig.SERVER_ADDRESS
  3.  
  4.     lateinit var apiService: ApiService
  5.  
  6.     companion object {
  7.         lateinit var httpClient: OkHttpClient
  8.     }
  9.  
  10.     init {
  11.         val retrofit = initRetrofit()
  12.         initServices(retrofit)
  13.     }
  14.  
  15.     private fun initRetrofit(): Retrofit {
  16.         val loggingInterceptor = HttpLoggingInterceptor().apply {
  17.             level = HttpLoggingInterceptor.Level.BODY
  18.         }
  19.  
  20.         val cookieManager = CookieManager()
  21.         cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL)
  22.  
  23.         val cacheSize = 10 * 1024 * 1024L // 10 MB
  24.         val cache = Cache(context.cacheDir, cacheSize)
  25.  
  26.         httpClient = OkHttpClient.Builder()
  27.             .readTimeout(45, TimeUnit.SECONDS)
  28.             .writeTimeout(45, TimeUnit.SECONDS)
  29.             .cookieJar(JavaNetCookieJar(cookieManager))
  30.             .addInterceptor(loggingInterceptor)
  31.             .addInterceptor({ chain ->
  32.                 try {
  33.                     chain.proceed(chain.request())
  34.                 } catch (e: Exception) {
  35.                     val offlineRequest = chain.request().newBuilder()
  36.                         .header(
  37.                             "Cache-Control", "public, only-if-cached," +
  38.                                     "max-stale=" + 60 * 60
  39.                         )
  40.                         .build()
  41.                     chain.proceed(offlineRequest)
  42.                 }
  43.             })
  44.             .cache(cache)
  45.             .build()
  46.  
  47.         return Retrofit.Builder()
  48.             .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
  49.             .addConverterFactory(GsonConverterFactory.create())
  50.             .client(httpClient)
  51.             .baseUrl(CURRENT_SERVER_ADDRESS)
  52.             .build()
  53.     }
  54.  
  55.     private fun initServices(retrofit: Retrofit) {
  56.         apiService = retrofit.create(ApiService::class.java)
  57.     }
  58.  
  59.     fun toRequestBody(value: String): RequestBody {
  60.         return RequestBody.create(MediaType.parse("text/plain"), value)
  61.     }
  62. }
Add Comment
Please, Sign In to add comment