1

私は実際に android.so で HttpResponse キャッシュを有効にしようとしています。このメソッドを呼び出して、onCreate メソッドのメイン アクティビティでキャッシュを有効にしました。

  private void enableHttpCaching()
   {
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
      {
        try {
          File httpCacheDir = new File(getApplicationContext().getCacheDir()
                  , "http");
          long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
          HttpResponseCache.install(httpCacheDir, httpCacheSize);
        } catch (IOException e) {
            e.printStackTrace();

        }        
    }
    else
    {
        File httpCacheDir = new File(getApplicationContext().getCacheDir()
                , "http");
        try {
            com.integralblue.httpresponsecache.HttpResponseCache.install
                (httpCacheDir, 10 * 1024 * 1024);
        } catch (IOException e) {       
            e.printStackTrace(); 
                    }
    }
  } 

しかし、サーバーデータが変更された場合にキャッシュを更新したいのですが、公式のdeveloper.androidでこの部分のコードを見つけました

  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
 }

私の質問は、更新をスキップする方法ですか? つまり、キャッシュからデータを取得する方法です。

これが私のgetJsonメソッドです

   public String getJSON(String url, int timeout) {
    try {
        URL u = new URL(url);
        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setRequestProperty("Content-length", "0");
        int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
        c.addRequestProperty("Cache-Control", "max-stale=" + maxStale);
        c.setUseCaches(true);
        c.setAllowUserInteraction(false);
        c.setConnectTimeout(timeout);
        c.setReadTimeout(timeout);
        c.connect();
        int status = c.getResponseCode();

        switch (status) {
            case 200:
            case 201:
                BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                   // sb.append(line+"\n");
                     sb.append(line);
                }
                br.close();
                return sb.toString();
        }

    } catch (MalformedURLException ex) {
        ex.printStackTrace();
        //Logger.getLogger(DebugServer.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        ex.printStackTrace();
        //Logger.getLogger(DebugServer.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

ご覧のとおり、サーバーデータが更新された場合、古いデータを取得するリスクがあります。更新を確認するために http 応答ヘッダーをテストするように最適化したいと考えています。

4

1 に答える 1

1

あなたが使用するプロトコルは何ですか?JSON、XML、その他の何か? HttpURLConnection から InputStream を解析する必要があります ( http://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html )

ところで、このライブラリをお勧めします:

  1. JSON の場合 — Gson ( http://code.google.com/p/google-gson/ )。
  2. XML 用 — SimpleXML ( http://simple.sourceforge.net/ )。

また役立つかもしれません:

InputStream を読み取る/文字列に変換する

于 2014-01-29T09:11:50.977 に答える