我正在开发一个Android应用程序,它有大量的web服务请求。
我已经有了一个LoginActivity,用户在其中引入用户名和密码,并使用结果和令牌进行服务器响应。然后,几个活动(它们都是从一个普通的BaseActivity扩展而来)执行大量的请求。
我还有一个ServiceManager类,它负责所有服务请求和HTTP请求。
我正在努力实现HttpResponseCache以减轻这个净负载。现在我有以下代码:
在我的LoginActivity(第一次启动)onCreate中:
//HTTP cache
try {
File httpCacheDir = new File(this.getCacheDir(), "http");
long httpCacheSize = 10 * 1024 * 1024; //10 MiB
HttpResponseCache.install(httpCacheDir, httpCacheSize);
Log.d(TAG, "Cache installed");
} catch (IOException e) {
Log.i(TAG, "HTTP response cache installation failed:" + e);
}在ServiceManager的httpRequest函数中,它是每次尝试发出HTTP请求时实际执行的函数:
//HTTPS connection
URL requestedUrl = new URL(uri);
httpsConnection = (HttpURLConnection) requestedUrl.openConnection();
httpsConnection.setUseCaches(true);
httpsConnection.setDefaultUseCaches(true);
httpsConnection.setRequestMethod("GET");
BufferedReader br = new BufferedReader(
new InputStreamReader(httpsConnection.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
httpResponse += line;
}
br.close();
httpsConnection.disconnect();
HttpResponseCache cache = HttpResponseCache.getInstalled();
Log.d(TAG, "Cache: " + cache);
if (cache != null) {
Log.d(TAG, "Net count: " + cache.getNetworkCount());
Log.d(TAG, "Hit count: " + cache.getHitCount());
Log.d(TAG, "Request count: " + cache.getRequestCount());
cache.flush();
}
try{
URI uriCached = new URI("<myurl>");
CacheResponse cr = cache.get(uriCached, "GET", null);
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(cr.getBody()));
while ((line = br.readLine()) != null) {
Log.d(TAG, line);
}
} catch (URISyntaxException e1) {
e1.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}现在,由于服务器端还没有准备好,我向其发出请求的URL总是相同的。
正如您所看到的,我正在调试一些东西,结果如下:
如您所见,当我通过cache.get()方法获得JSON时,缓存能够读取JSON,但它从未命中。
响应头中的服务器端指令Cache-Control是: Cache-Control:public Cache-Control:max-age=3800
为什么缓存从来都没有命中?
非常感谢!
发布于 2015-12-02 12:42:34
我发现了问题。
我试图将请愿书缓存到返回JSON的PHP。PHP总是被认为是动态内容(实际上是动态内容),而且从来没有缓存过。
尝试仅缓存JSON应用程序端而不是服务器端时要遵循的路径。这样,它就不会提出请求了。
最好的。
编辑
毫无疑问,解决这种麻烦的最好办法是使用截击。
https://stackoverflow.com/questions/34037179
复制相似问题