Search code examples
javaandroidhttphttpresponsecache

parsing Android HttpResponse cache update?


I am actually trying to enable HttpResponse cache in my android.so i 've enabled my cache in my main activty in the onCreate Method by calling this method:

  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(); 
                    }
    }
  } 

But i want my cache to be updated if the server data is modified i found this portion of code in the official 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
 }

My question is how to skip the update? What i mean is how to get the data from the cache?

Here is my getJson method

   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;
}

as you see i risk to get stale data if server data is updated .i want to optimize it to test the http response header to check for updates


Solution

  • what protocol you use? JSON, XML, something else? You need parse InputStream from HttpURLConnection (http://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html)

    By the way, i suggest you this libraries:

    1. for JSON — Gson (http://code.google.com/p/google-gson/).
    2. for XML — SimpleXML (http://simple.sourceforge.net/).

    Also may be helpful:

    Read/convert an InputStream to a String