性能优化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

发布了229 篇原创文章 · 获赞 72 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/baopengjian/article/details/104186789