キャッシュのパフォーマンスの最適化要求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は、再びは直接リクエストを要求しない、行くGETキャッシュ

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妥当性を動的に制御することができます

// 5秒以内に要求サーバを識別しません。

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

サーバー側のデモ:

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デモ

CacheActivity

公開された229元の記事 ウォン称賛72 ビュー15万+

おすすめ

転載: blog.csdn.net/baopengjian/article/details/104186789