給Retrofit添加離線緩存,支持Post請求

須要實現的需求:

有網絡的時候使用網絡獲取數據,網絡不可用的狀況下使用本地緩存。 Retrofit自己並無能夠設置緩存的api,它的底層網絡請求使用Okhttp,因此添加緩存也得從Okhttp入手。html

一.Okhttp自帶的緩存支持:

首先設置緩存目錄,Okhttp的緩存用到了DiskLruCache這個類。java

OkHttpClient.Builder builder = new OkHttpClient.Builder();
        File cacheDir = new File(context.getCacheDir(), "response");
        //緩存的最大尺寸10m
        Cache cache = new Cache(cacheDir, 1024 * 1024 * 10);
        builder.cache(cache);
複製代碼

Okhttp緩存攔截器:android

public class CacheInterceptor implements Interceptor {

    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        boolean netAvailable = NetWorkUtil.isNetAvailable(AppIml.appContext);

        if (netAvailable) {
            request = request.newBuilder()
                    //網絡可用 強制從網絡獲取數據
                    .cacheControl(CacheControl.FORCE_NETWORK)
                    .build();
        } else {
            request = request.newBuilder()
                    //網絡不可用 從緩存獲取
                    .cacheControl(CacheControl.FORCE_CACHE)
                    .build();
        }
        Response response = chain.proceed(request);
        if (netAvailable) {
            response = response.newBuilder()
                    .removeHeader("Pragma")
                    // 有網絡時 設置緩存超時時間1個小時
                    .header("Cache-Control", "public, max-age=" + 60 * 60)
                    .build();
        } else {
            response = response.newBuilder()
                    .removeHeader("Pragma")
                    // 無網絡時,設置超時爲1周
                    .header("Cache-Control", "public, only-if-cached, max-stale=" + 7 * 24 * 60 * 60)
                    .build();
        }
        return response;
    }
}
複製代碼

給OkHttpClient 設置攔截器,並用咱們建立的OkHttpClient 替代Retrofit 默認的OkHttpClient:git

builder.addInterceptor(new CacheInterceptor());

    OkHttpClient client = builder.build();
    Retrofit retrofit = new Retrofit.Builder()
            .client(client)
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
複製代碼

到這裏Okhttp的緩存就配置完成了,實現了開頭所提出的需求。 可是這裏有個問題,Okhttp是隻支持Get請求的,若是咱們使用其餘方式請求好比Post,請求的可以回調onResponse方法,可是經過 response.body()來獲取請求的數據會獲得null, response.code()獲得的是504。 我還目前沒有找到可以讓Okhttp的緩存支持Post方式的方法,因此我只能本身去實現緩存機制。github

二.本身手動添加緩存支持:

首先將 DiskLruCache.java 添加進來,咱們和Okhttp同樣使用它來實現磁盤緩存策略。 關於DiskLruCache的源碼分析:Android DiskLruCache徹底解析,硬盤緩存的最佳方案。 寫一個工具類 來設置和獲取緩存:json

public final class CacheManager {

    public static final String TAG = "CacheManager";

    //max cache size 10mb
    private static final long DISK_CACHE_SIZE = 1024 * 1024 * 10;

    private static final int DISK_CACHE_INDEX = 0;

    private static final String CACHE_DIR = "responses";

    private DiskLruCache mDiskLruCache;

    private volatile static CacheManager mCacheManager;

    public static CacheManager getInstance() {
        if (mCacheManager == null) {
            synchronized (CacheManager.class) {
                if (mCacheManager == null) {
                    mCacheManager = new CacheManager();
                }
            }
        }
        return mCacheManager;
    }

    private CacheManager() {
        File diskCacheDir = getDiskCacheDir(AppIml.appContext, CACHE_DIR);
        if (!diskCacheDir.exists()) {
            boolean b = diskCacheDir.mkdirs();
            Log.d(TAG, "!diskCacheDir.exists() --- diskCacheDir.mkdirs()=" + b);
        }
        if (diskCacheDir.getUsableSpace() > DISK_CACHE_SIZE) {
            try {
                mDiskLruCache = DiskLruCache.open(diskCacheDir,
                        getAppVersion(AppIml.appContext), 1/*一個key對應多少個文件*/, DISK_CACHE_SIZE);
                Log.d(TAG, "mDiskLruCache created");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 同步設置緩存
     */
    public void putCache(String key, String value) {
        if (mDiskLruCache == null) return;
        OutputStream os = null;
        try {
            DiskLruCache.Editor editor = mDiskLruCache.edit(encryptMD5(key));
            os = editor.newOutputStream(DISK_CACHE_INDEX);
            os.write(value.getBytes());
            os.flush();
            editor.commit();
            mDiskLruCache.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 異步設置緩存
     */
    public void setCache(final String key, final String value) {
        new Thread() {
            @Override
            public void run() {
                putCache(key, value);
            }
        }.start();
    }

    /**
     * 同步獲取緩存
     */
    public String getCache(String key) {
        if (mDiskLruCache == null) {
            return null;
        }
        FileInputStream fis = null;
        ByteArrayOutputStream bos = null;
        try {
            DiskLruCache.Snapshot snapshot = mDiskLruCache.get(encryptMD5(key));
            if (snapshot != null) {
                fis = (FileInputStream) snapshot.getInputStream(DISK_CACHE_INDEX);
                bos = new ByteArrayOutputStream();
                byte[] buf = new byte[1024];
                int len;
                while ((len = fis.read(buf)) != -1) {
                    bos.write(buf, 0, len);
                }
                byte[] data = bos.toByteArray();
                return new String(data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 異步獲取緩存
     */
    public void getCache(final String key, final CacheCallback callback) {
        new Thread() {
            @Override
            public void run() {
                String cache = getCache(key);
                callback.onGetCache(cache);
            }
        }.start();
    }

    /**
     * 移除緩存
     */
    public boolean removeCache(String key) {
        if (mDiskLruCache != null) {
            try {
                return mDiskLruCache.remove(encryptMD5(key));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * 獲取緩存目錄
     */
    private File getDiskCacheDir(Context context, String uniqueName) {
        String cachePath = context.getCacheDir().getPath();
        return new File(cachePath + File.separator + uniqueName);
    }

    /**
     * 對字符串進行MD5編碼
     */
    public static String encryptMD5(String string) {
        try {
            byte[] hash = MessageDigest.getInstance("MD5").digest(
                    string.getBytes("UTF-8"));
            StringBuilder hex = new StringBuilder(hash.length * 2);
            for (byte b : hash) {
                if ((b & 0xFF) < 0x10) {
                    hex.append("0");
                }
                hex.append(Integer.toHexString(b & 0xFF));
            }
            return hex.toString();
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return string;
    }

    /**
     * 獲取APP版本號
     */
    private int getAppVersion(Context context) {
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            return pi == null ? 0 : pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
複製代碼

而後咱們仍是給Okhttp添加攔截器,將請求的Request和請求結果Response以Key Value的形式緩存的磁盤。這裏的重點是判斷請求的方式,若是是Post請求這將請求的body轉成String而後添加到url的後面做爲磁盤緩存的key。api

public class EnhancedCacheInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);

        String url = request.url().toString();
        RequestBody requestBody = request.body();
        Charset charset = Charset.forName("UTF-8");
        StringBuilder sb = new StringBuilder();
        sb.append(url);
        if (request.method().equals("POST")) {
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(Charset.forName("UTF-8"));
            }
            Buffer buffer = new Buffer();
            try {
                requestBody.writeTo(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            sb.append(buffer.readString(charset));
            buffer.close();
        }
        Log.d(CacheManager.TAG, "EnhancedCacheInterceptor -> key:" + sb.toString());

        ResponseBody responseBody = response.body();
        MediaType contentType = responseBody.contentType();

        BufferedSource source = responseBody.source();
        source.request(Long.MAX_VALUE);
        Buffer buffer = source.buffer();

        if (contentType != null) {
            charset = contentType.charset(Charset.forName("UTF-8"));
        }
        String key = sb.toString();
        //服務器返回的json原始數據 
        String json = buffer.clone().readString(charset);

        CacheManager.getInstance().putCache(key, json);
        Log.d(CacheManager.TAG, "put cache-> key:" + key + "-> json:" + json);
        return chain.proceed(request);
    }
}
複製代碼

建立OkHttpClient並添加緩存攔截器,初始化Retrofit;緩存

OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.addInterceptor(new EnhancedCacheInterceptor());

        OkHttpClient client = builder.build();
        Retrofit retrofit = new Retrofit.Builder()
                .client(client)
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
複製代碼

到這裏咱們已經實現了請求網絡添加緩存,下一步是在網絡不可用的時候獲取磁盤上的緩存,這裏我經過改造Call和Callback來實現: EnhancedCall使用裝飾模式裝飾Retrofit的Call,EnhancedCallback比Retrofit的Callback接口多一個onGetCache方法。 網絡不可用的時候會回調onFailure方法,咱們攔截onFailure,並根據請求Request去獲取緩存,獲取到緩存走EnhancedCallback的onGetCache方法,若是沒有獲取到緩存或者請求不須要使用緩存再調用onFailure方法,bash

public class EnhancedCall<T> {
    private Call<T> mCall;
    private Class dataClassName;
    // 是否使用緩存 默認開啓
    private boolean mUseCache = true;

    public EnhancedCall(Call<T> call) {
        this.mCall = call;
    }

    /**
     * Gson反序列化緩存時 須要獲取到泛型的class類型
     */
    public EnhancedCall<T> dataClassName(Class className) {
        dataClassName = className;
        return this;
    }

    /**
     * 是否使用緩存 默認使用
     */
    public EnhancedCall<T> useCache(boolean useCache) {
        mUseCache = useCache;
        return this;
    }

    public void enqueue(final EnhancedCallback<T> enhancedCallback) {
        mCall.enqueue(new Callback<T>() {
            @Override
            public void onResponse(Call<T> call, Response<T> response) {
                enhancedCallback.onResponse(call, response);
            }

            @Override
            public void onFailure(Call<T> call, Throwable t) {
                if (!mUseCache || NetWorkUtil.isNetAvailable(AppIml.appContext)) {
                    //不使用緩存 或者網絡可用 的狀況下直接回調onFailure
                    enhancedCallback.onFailure(call, t);
                    return;
                }

                Request request = call.request();
                String url = request.url().toString();
                RequestBody requestBody = request.body();
                Charset charset = Charset.forName("UTF-8");
                StringBuilder sb = new StringBuilder();
                sb.append(url);
                if (request.method().equals("POST")) {
                    MediaType contentType = requestBody.contentType();
                    if (contentType != null) {
                        charset = contentType.charset(Charset.forName("UTF-8"));
                    }
                    Buffer buffer = new Buffer();
                    try {
                        requestBody.writeTo(buffer);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    sb.append(buffer.readString(charset));
                    buffer.close();
                }

                String cache = CacheManager.getInstance().getCache(sb.toString());
                Log.d(CacheManager.TAG, "get cache->" + cache);

                if (!TextUtils.isEmpty(cache) && dataClassName != null) {
                    Object obj = new Gson().fromJson(cache, dataClassName);
                    if (obj != null) {
                        enhancedCallback.onGetCache((T) obj);
                        return;
                    }
                }
                enhancedCallback.onFailure(call, t);
                Log.d(CacheManager.TAG, "onFailure->" + t.getMessage());
            }
        });
    }
}
複製代碼
public interface EnhancedCallback<T> {
    void onResponse(Call<T> call, Response<T> response);

    void onFailure(Call<T> call, Throwable t);

    void onGetCache(T t);
}
複製代碼

到這裏已經實現了最開始的個人需求,也能夠支持Post請求的緩存。最後看看使用的方式:服務器

public void getRequest(View view) {
        ApiService service = getApiService();
        Call<UserList> call = service.getUserList();
        //使用咱們本身的EnhancedCall 替換Retrofit的Call
        EnhancedCall<UserList> enhancedCall = new EnhancedCall<>(call);
        enhancedCall.useCache(true)/*默認支持緩存 可不設置*/
                .dataClassName(UserList.class)
                .enqueue(new EnhancedCallback<UserList>() {
                    @Override
                    public void onResponse(Call<UserList> call, Response<UserList> response) {
                        UserList userlist = response.body();
                        if (userlist != null) {
                            Log.d(TAG, "onResponse->" + userlist.toString());
                        }
                    }

                    @Override
                    public void onFailure(Call<UserList> call, Throwable t) {
                        Log.d(TAG, "onFailure->" + t.getMessage());
                    }

                    @Override
                    public void onGetCache(UserList userlist) {
                        Log.d(TAG, "onGetCache" + userlist.toString());
                    }
                });
    }
複製代碼

所有代碼地址Github:https://github.com/wangyiwy/CacheUtil4Retrofit)

相關文章
相關標籤/搜索