日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

HttpResponseCache的使用缓存cache

發(fā)布時(shí)間:2025/4/14 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 HttpResponseCache的使用缓存cache 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

為什么要用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的好處:

  • 明顯一點(diǎn)節(jié)約電,減少了網(wǎng)絡(luò)請(qǐng)求。
  • 開(kāi)發(fā)者不用自己在去寫(xiě)cache機(jī)制了。
  • 最根本的一點(diǎn)就是,如果開(kāi)發(fā)者在開(kāi)發(fā)中不是使用的HttpClient, HttpDefaultClient..., 而是用 HttpURLConnection的話, 你根本不用改本來(lái)的 Code
  • 這個(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)題。

    如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。