HttpResponseCache的使用缓存cache
為什么要用cache?
?我們可以通過傳遞類似上次更新時間這樣的參數來制定查詢某些數據。同樣,在下載圖片的時候,server那邊最好能夠減少圖片的大小,而不是讓我們下載完整大小的圖片。
之前我們在軟件開發中,cache都是自己來寫,不管是圖片緩存還是其他從網絡獲取的數據,有了HttpResponseCache,它幫助我們可以很好的解決cache這個問題(我現在感覺他只適合cache一些小的數據,如果大量的圖片cache還是自己緩存到SD卡上面去比較好)。
?HttpResponseCache的好處:
這個我們就不多說了,直接看示例:
在開發中你不用寫其他任何東西,只要在Application層將其啟動就好了 其他的全部交給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);}}}接下來我們來看看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;}}}?
我們看下效果:
看下緩存文件,每個文件會產生兩個文件,一個是數據文件,一個是http header 信息
?
?
?
?Cache Files Locally [緩存文件到本地]
?
- 避免下載重復的數據是很重要的。可以使用緩存機制來處理這個問題。緩存static的資源,例如完整的圖片。這些緩存的資源需要分開存放。
- 為了保證app不會因為緩存而導致顯示的是舊數據,請從緩存中獲取最新的數據,當數據過期的時候,會提示進行刷新。
?
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 }?
使用這種方法,可以有效保證緩存里面一直是最新的數據。可以使用下面的方法來獲取外部緩存的目錄:
Context.getExternalCacheDir();下面是獲取內部緩存的方法,請注意,存放在內存中的數據有可能因內部空間不夠而被清除。
?
Context.getCache();?
不管是存放在哪里的文件都會在app卸載的時候被清除。
?
?
?
?
轉載于:https://www.cnblogs.com/mingfeng002/p/3493778.html
總結
以上是生活随笔為你收集整理的HttpResponseCache的使用缓存cache的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: @@ROWCOUNT 含义
- 下一篇: 性能测试的方法