天天看點

Android網絡緩存

主要介紹可同步或異步擷取資料、可自動根據伺服器的傳回頭判斷是否需要緩存、可自動根據請求頭資訊判斷是否讀取緩存的網絡緩存。

本文分為四部分包括使用示例、功能介紹、原理介紹、疑問解答。

适用:網絡擷取内容不大的應用,尤其是api接口資料,如新浪微網誌、twitter的timeline、微信公衆賬号發送的内容等等。

Android網絡緩存

1、使用

(1)引入公共庫

(2)調用

僅需簡單兩步:

a. 定義緩存

Java

1

private HttpCache httpCache = new HttpCache(context);

或擷取全局唯一執行個體HttpCache

private HttpCache httpCache = CacheManager.getHttpCache(context);

b. 調用httpGet函數同步或異步擷取網絡資料

以httpGet函數異步擷取資料為例,其他接口見第2部分介紹

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

httpCache.httpGet("http://www.trinea.cn/", new HttpCacheListener() {

protected void onPreGet() {

// do something like show progressBar before httpGet, runs on the UI thread

}

protected void onPostGet(HttpResponse httpResponse, boolean isInCache) {

// do something like show data after httpGet, runs on the UI thread

if (httpResponse != null) {

// get data success

setText(httpResponse.getResponseBody());

} else {

// get data fail

});

(3) 要求

緩存過期時間是根據伺服器傳回頭中的cache-control和expires決定的,是以伺服器需要設定這兩個參數才能生效。具體可見第3部分原理介紹

2、功能介紹

(1) 幾個相關類

HttpRequest 請求資訊類,可設定逾時時間、請求參數、UserAgent、請求屬性等

HttpResponse 請求資料傳回類,可擷取接口内容、過期時間等。

HttpCacheListener 請求回調接口,onPreGet方法會在請求前執行,onPostGet方法會在請求結束後執行,兩個方法都運作在UI線程

(2) 構造函數

目前的構造函數僅有一個,後面增加二級緩存可能會添加另外的構造函數

public HttpCache(Context context)

(3) 異步擷取網絡資料

public void httpGet(String url, HttpCacheListener listener)

根據url擷取資料,擷取前自動調用listener的onPreGet方法,擷取後自動調用listener的onPostGet方法

public void httpGet(HttpRequest request, HttpCacheListener listener)

根據request擷取資料,擷取前自動調用listener的onPreGet方法,擷取後自動調用listener的onPostGet方法

(4) 同步擷取網絡資料

public String httpGetString(String url)

根據url擷取資料,網絡錯誤傳回null,否則傳回資料為string

public HttpResponse httpGet(String url)

根據url擷取資料,網絡錯誤傳回null,否則傳回資料以HttpResponse.getResponseBody()擷取

public HttpResponse httpGetString(HttpRequest httpRequest)

根據request擷取資料,網絡錯誤傳回null,否則傳回資料為string

public HttpResponse httpGet(HttpRequest request)

(5) 其他

public boolean containsKey(String url) 判斷某個url是否已經在緩存中并且有效

public void clear() 清空緩存

3、原理介紹

<a href="http://www.trinea.cn/test-for-http-cache.html">http://www.trinea.cn/test-for-http-cache.html</a>

用chrome檢視截圖如下:

Android網絡緩存

4、疑問解答

(1) 緩存時間是多少或為什麼我的url始終不緩存

緩存時間是根據伺服器的傳回時間決定的,詳見上面第3部分原理介紹

(2) 如果某次請求不想使用緩存資料或傳回資料不想被緩存怎麼辦

a. 某次請求不想使用緩存

在調用httpGet方法時設定入參HttpRequest,如下:

request.setRequestProperty(“cache-control”, “no-cache”);

b. 某次請求傳回資料不想被緩存

request.setRequestProperty(“cache-control”, “no-store”);

繼續閱讀