HttpResponseCache的使用缓存cache
為什么要用cache?
?我們可以通過(guò)傳遞類(lèi)似上次更新時(shí)間這樣的參數(shù)來(lái)制定查詢(xún)某些數(shù)據(jù)。同樣,在下載圖片的時(shí)候,server那邊最好能夠減少圖片的大小,而不是讓我們下載完整大小的圖片。
之前我們?cè)谲浖_(kāi)發(fā)中,cache都是自己來(lái)寫(xiě),不管是圖片緩存還是其他從網(wǎng)絡(luò)獲取的數(shù)據(jù),有了HttpResponseCache,它幫助我們可以很好的解決cache這個(gè)問(wèn)題(我現(xiàn)在感覺(jué)他只適合cache一些小的數(shù)據(jù),如果大量的圖片cache還是自己緩存到SD卡上面去比較好)。
?HttpResponseCache的好處:
這個(gè)我們就不多說(shuō)了,直接看示例:
在開(kāi)發(fā)中你不用寫(xiě)其他任何東西,只要在Application層將其啟動(dòng)就好了 其他的全部交給HttpURLConnection處理就行。
public class HttpCacheApplication extends Application {@Overridepublic void onCreate() {super.onCreate();new Thread() {@Overridepublic void run() {enableHttpResponseCache();}}.start();}private void enableHttpResponseCache() {try {long httpCacheSize = 10 * 1024 * 1024;// 10MFile httpCacheDir = new File(getCacheDir(), "http");Class.forName("android.net.http.HttpResponseCache").getMethod("install", File.class, long.class).invoke(null, httpCacheDir, httpCacheSize);} catch (Exception e) {Log.e("===>", e.getMessage(), e);}}}接下來(lái)我們來(lái)看看HttpUrlConnection是怎么處理的,怎么緩存的。
?
public class MainActivity extends Activity {private final String TAG = getClass().getSimpleName();ImageView img;Button msg;TextView tv;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);img = (ImageView) findViewById(R.id.imageView1);tv = (TextView)findViewById(R.id.textView1);msg = (Button) findViewById(R.id.button1);msg.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {new InternetTask().execute();}});findViewById(R.id.button2).setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {MainActivity.this.finish();}});}class InternetTask extends AsyncTask<String, String, Boolean> {Bitmap bitmap;String jsonStr;@Overrideprotected void onPostExecute(Boolean result) {super.onPostExecute(result);img.setImageBitmap(bitmap);tv.setText(jsonStr);}@Overrideprotected Boolean doInBackground(String... params) {// Test download imagetry {URL url = new URL("http://news.baidu.com/resource/img/logo_news_137_46.png");HttpURLConnection conn = (HttpURLConnection) (url.openConnection());conn.connect();InputStream is = conn.getInputStream();BitmapFactory.Options ops = new BitmapFactory.Options();bitmap = BitmapFactory.decodeStream(is, null, ops);is.close();conn.disconnect(); } catch (Exception e) {Log.e(TAG, e.getMessage(), e);}// Test download JSON datatry {URL url = new URL("http://www.baidu.com/");HttpURLConnection conn = (HttpURLConnection) (url.openConnection());conn.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));jsonStr = reader.readLine();InputStream is = conn.getInputStream();is.close();conn.disconnect();} catch (Exception e) {Log.e(TAG, e.getMessage(), e);}return true;}}}?
我們看下效果:
看下緩存文件,每個(gè)文件會(huì)產(chǎn)生兩個(gè)文件,一個(gè)是數(shù)據(jù)文件,一個(gè)是http header 信息
?
?
?
?Cache Files Locally [緩存文件到本地]
?
- 避免下載重復(fù)的數(shù)據(jù)是很重要的。可以使用緩存機(jī)制來(lái)處理這個(gè)問(wèn)題。緩存static的資源,例如完整的圖片。這些緩存的資源需要分開(kāi)存放。
- 為了保證app不會(huì)因?yàn)榫彺娑鴮?dǎo)致顯示的是舊數(shù)據(jù),請(qǐng)從緩存中獲取最新的數(shù)據(jù),當(dāng)數(shù)據(jù)過(guò)期的時(shí)候,會(huì)提示進(jìn)行刷新。
?
long currentTime = System.currentTimeMillis()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); long expires = conn.getHeaderFieldDate("Expires", currentTime); long lastModified = conn.getHeaderFieldDate("Last-Modified", currentTime); setDataExpirationDate(expires); if (lastModified < lastUpdateTime) { // Skip update } else { // Parse update }?
使用這種方法,可以有效保證緩存里面一直是最新的數(shù)據(jù)。可以使用下面的方法來(lái)獲取外部緩存的目錄:
Context.getExternalCacheDir();下面是獲取內(nèi)部緩存的方法,請(qǐng)注意,存放在內(nèi)存中的數(shù)據(jù)有可能因內(nèi)部空間不夠而被清除。
?
Context.getCache();?
不管是存放在哪里的文件都會(huì)在app卸載的時(shí)候被清除。
?
?
?
?
轉(zhuǎn)載于:https://www.cnblogs.com/mingfeng002/p/3493778.html
總結(jié)
以上是生活随笔為你收集整理的HttpResponseCache的使用缓存cache的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: @@ROWCOUNT 含义
- 下一篇: 性能测试的方法