#caching in retofit in android studio
Explore tagged Tumblr posts
jeeteshsurana · 6 years ago
Photo
Tumblr media
Http ApiClient Caching http://bit.ly/2uJuhZQ
0 notes
jeeteshsurana · 6 years ago
Text
Http ApiClient Caching
http://bit.ly/2OP8MzX
Http ApiClient Caching in Android
import android.content.Context
import android.util.Log
import com.commonlibs.util.helper.NetworkManager
import com.google.gson.Gson
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import okhttp3.Cache
import okhttp3.CacheControl
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit
/**
 * Api Client for retrofit Instance with Base Url
 */
class APIClient {
    private var mRetrofit: Retrofit? = null
    private val TAG = "RetrofitManager"
    private val mHeaderCacheControl = "Cache-Control"
    private val mHeaderPragma = "Pragma"
    private var mCache: Cache? = null
    private var mOkHttpClient: OkHttpClient? = null
    /**
     * getClient Retorfit instance
     * @param mContext use for store caching
     * @param mAPI  search for base url
     */
    fun getClient(mContext: Context, mAPI: Int): Retrofit {
        if (mRetrofit == null) {
            val interceptor = HttpLoggingInterceptor()
            interceptor.level = HttpLoggingInterceptor.Level.BODY
            mRetrofit = Retrofit.Builder()
                .baseUrl(apiUrl(mAPI))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .client(getOkHttpClient(mContext))
                .build()
        }
        return mRetrofit!!
    }
    /**
     * Api url use to choose ase url
     * @param selectUrl send number and get base url like 0-> 8800
     */
    private fun apiUrl(selectUrl: Int): String {
        return when (selectUrl) {
            0 -> Constants.authURL
            1 -> Constants.inventoryURL
            2 -> Constants.merchantURL
            3 -> Constants.customerURL
            4 -> Constants.paymentURL
            5 -> Constants.notificationURL
            6 -> Constants.auctionURL
            7 -> Constants.storeURL
            8 -> Constants.shippingURL
            else -> Constants.authURL
        }
    }
    /**
     * getOkHttpClient
     * @param mContext use for store caches
     */
    private fun getOkHttpClient(mContext: Context): OkHttpClient {
        val cacheSize = 10 * 1024 * 1024 // 10 MB
        val httpCacheDirectory = File(mContext.cacheDir, Constants.httpCacheDirectory)
        val cache = Cache(httpCacheDirectory, cacheSize.toLong())
        val networkCacheInterceptor = Interceptor { chain ->
            val response = chain.proceed(chain.request())
            val cacheControl = CacheControl.Builder()
                .maxAge(2, TimeUnit.HOURS)
                .build()
            response.newBuilder()
                .header(Constants.cacheControl, cacheControl.toString())
                .build()
        }
        val loggingInterceptor = HttpLoggingInterceptor()
        loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
        return OkHttpClient.Builder()
            .connectTimeout(3, TimeUnit.MINUTES)
            .readTimeout(90, TimeUnit.SECONDS)
            .writeTimeout(45, TimeUnit.SECONDS)
            .addInterceptor(loggingInterceptor)
            .cache(cache)
            .addNetworkInterceptor(networkCacheInterceptor)
            .build()
    }
    /**
     * this client use for User Access APIs
     */
    val client: Retrofit
        get() {
            if (mRetrofit == null) {
                val loggingInterceptor = HttpLoggingInterceptor()
                loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
                val okHttpClient = OkHttpClient.Builder()
                    .addInterceptor(loggingInterceptor)
                    .addInterceptor(BasicAuthInterceptor(Constants.authHeaderUserName, Constants.authHeaderPassword))
                    .connectTimeout(Constants.http_timeout.toLong(), TimeUnit.SECONDS)
                    .connectTimeout(3, TimeUnit.MINUTES)
                    .readTimeout(90, TimeUnit.SECONDS)
                    .writeTimeout(45, TimeUnit.SECONDS)
                    .build()
                mRetrofit = retrofit2.Retrofit.Builder()
                    .baseUrl(Constants.authURL)
                    .client(okHttpClient)
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build()
            }
            return mRetrofit!!
        }
    fun getRetrofitCache(mContext : Context, mAPI: Int): Retrofit {
        if (mRetrofit == null) {
            val httpClient = OkHttpClient.Builder()
                .addInterceptor(provideOfflineCacheInterceptor(mContext))
                .addNetworkInterceptor(provideCacheInterceptor(mContext))
                .cache(provideCache(mContext))
            mOkHttpClient = httpClient.build()
            mRetrofit = Retrofit.Builder()
                .baseUrl(apiUrl(mAPI))
                .addConverterFactory(GsonConverterFactory.create(Gson()))
                .client(mOkHttpClient!!)
                .build()
        }
        return mRetrofit!!
    }
    //Cache store with size
    private fun provideCache(mContext : Context): Cache? {
        if (mCache == null) {
            try {
                mCache = Cache(
                    File(mContext.cacheDir, "http-cache"),
                    100 * 1024 * 1024) // 10 MB
            } catch (e: Exception) {
                Log.e(TAG, "Could not create Cache!")
            }
        }
        return mCache
    }
    //get the cache and remove particular time
    private fun provideCacheInterceptor(mContext : Context): Interceptor {
        return Interceptor { chain ->
            val response = chain.proceed(chain.request())
            val cacheControl: CacheControl = if (NetworkManager(mContext).checkInternetConnection()) {
                CacheControl.Builder()
                    .maxAge(0, TimeUnit.SECONDS)
                    .build()
            } else {
                CacheControl.Builder()
                    .maxStale(7, TimeUnit.DAYS)
                    .build()
            }
            response.newBuilder()
                .removeHeader(mHeaderPragma)
                .removeHeader(mHeaderCacheControl)
                .header(mHeaderCacheControl, cacheControl.toString())
                .build()
        }
    }
    //getting the caches if internet are not available
    private fun provideOfflineCacheInterceptor(mContext: Context): Interceptor {
        return Interceptor { chain ->
            var request = chain.request()
            if (!NetworkManager(mContext).checkInternetConnection()) {
                val cacheControl = CacheControl.Builder()
                    .maxStale(7, TimeUnit.DAYS)
                    .build()
                request = request.newBuilder()
                    .removeHeader(mHeaderPragma)
                    .removeHeader(mHeaderCacheControl)
                    .cacheControl(cacheControl)
                    .build()
            }
            chain.proceed(request)
        }
    }
}
//String.xml
    <!--Common String-->
    <string name="AppTag">TAG</string>
    <!--Message-->
    <string name="msg_cache">Could not create Cache!</string>
    <!--constant-->
    <string name="cons_http">http-cache</string>
//Constant.kt
open class Constants {
    companion object {
       var authURL: String = "your_url"
        var inventoryURL: String = "your_url"
        var merchantURL: String = "your_url"
        var customerURL: String = "your_url"
        var paymentURL: String = "your_url"
        var notificationURL: String = "your_url"
        var auctionURL: String = "your_url"
        var storeURL: String = "your_url"
        var shippingURL: String = "your_url"
    }
}
//NetworkManager.kt
import android.content.Context
import android.net.ConnectivityManager
class NetworkManager constructor(mContext: Context?) {
    var mContext: Context? = null
    init {
        this.mContext = mContext!!
    }
    /* class for checking Internet connectivity */
    fun checkInternetConnection(): Boolean {
        if (mContext == null) return false
        var con_manager: ConnectivityManager =
            mContext!!.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        return con_manager .activeNetworkInfo != null && con_manager.activeNetworkInfo.isConnected
    }
}
//how to Applied 
 private val apiServicesCache = APIClient().getRetrofitCache(mBaseActivity, 1).create(RetrofitInterface::class.java)!!
/**
     * Get Product Full Detail
     * @param id product id
     */
    fun getProductFullDetail(id: String): LiveData<ProductFullDetail> {
        Log.d("TAG", "Similar Product id=$id")
                 val call = apiServicesCache.getProductFullDetails(id)
        call.enqueue(object : Callback<ProductFullDetail> {
            override fun onResponse(call: Call<ProductFullDetail>, response: Response<ProductFullDetail>) {
                if (response.isSuccessful) {
                    mProductFullDetail.value = response.body()
                }else {
                    mBaseActivity.showApiError(response.code().toString())
                }
            }
            override fun onFailure(call: Call<ProductFullDetail>, t: Throwable) {
                mBaseActivity.showApiError(t.message.toString())
            }
        })
        return this.mProductFullDetail
    }
//RetrofitInterface.kt
interface RetrofitInterface {
 @GET("products/{id}")
    fun getProductFullDetails(@Path("id") id: String): Call<ProductFullDetail>
}
  via Blogger http://bit.ly/2uJuhZQ
0 notes