1 設置緩存
Android系統默認的HttpResponseCache(網絡請求響應緩存)是關閉的
//這樣開啓,開啓緩存之後會在cache目錄下面創建http的文件夾,HttpResponseCache會緩存所有的返回信息
File cacheDir = new File(getCacheDir(), "http");//緩存目錄
long maxSize = 10 * 1024 * 1024;//緩存大小,單位byte
HttpResponseCache.install(cacheDir, maxSize);
2 再次請求時,不直接請求,先去獲取緩存
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 服務器端可以動態控制緩存的有效期
//標識五秒之內不會再請求服務器
response.addHeader("Cache-control", "max-age=5");
服務器端Demo:
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();
}
}