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 ( http://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html )解析 InputStream

顺便说一句,我建议你这个库:

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

也可能有帮助:

将 InputStream 读取/转换为字符串

于 2014-01-29T09:11:50.977 回答