性能優化11_Http請求緩存

Android性能優化彙總

1 設置緩存

Android系統默認的HttpResponseCache(網絡請求響應緩存)是關閉的

//這樣開啓,開啓緩存之後會在cache目錄下面創建http的文件夾,HttpResponseCache會緩存所有的返回信息
 File cacheDir = new File(getCacheDir(), "http");//緩存目錄
 long maxSize = 10 * 1024 * 1024;//緩存大小,單位byte
 HttpResponseCache.install(cacheDir, maxSize);

2 再次請求時,不直接請求,先去獲取緩存

new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    HttpURLConnection conn = (HttpURLConnection) new URL(URL1).openConnection();
                    conn.setRequestMethod("GET");
                    conn.setDoInput(true);
                    conn.connect();
                    int responseCode = conn.getResponseCode();
                    if(responseCode== 200){
                        InputStream is = conn.getInputStream();
                        BufferedReader br = new BufferedReader(new InputStreamReader(is));
                        Log.d("CacheActivity", br.readLine());
                    }else{
                        Log.d("CacheActivity",responseCode+"" );
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    Log.d("CacheActivity","請求異常:"+e.getMessage());
                }
            }
 }).start();

3 服務器端可以動態控制緩存的有效期

//標識五秒之內不會再請求服務器

response.addHeader("Cache-control", "max-age=5");

服務器端Demo:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//給客戶端響應一個json字符串
		PrintWriter writer = response.getWriter();
		Gson gson = new Gson();
		JsonObject json = new JsonObject();
		json.addProperty("isValid", true);
		json.addProperty("description", "information");
		writer.write(gson.toJson(json));
		//標識五秒之內不會再請求服務器
		response.addHeader("Cache-control", "max-age=5");
		
}

4 客戶端刪除緩存

 HttpResponseCache cache = HttpResponseCache.getInstalled();
        if(cache != null){
            try {
                cache.delete();
                Log.d("CacheActivity","清除緩存");
            } catch (IOException e) {
                e.printStackTrace();
            }
 }

5 Demo

CacheActivity

發佈了231 篇原創文章 · 獲贊 75 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章