我正在使用基于 NanoHTTPD 构建的自定义 Web 服务器,并添加了缓存功能。代码中只有一部分可能会引发 304 Not Modified 响应:
if(isNotModified(f,header,parms)){// if requested file has not been modified, let's make the browser use it's cache
Response r= new Response( Response.Status.NOT_MODIFIED, MIME_PLAINTEXT,(String)null,null);
//r.addHeader(key,val);
r.addHeader("Last-Modified",""+f.lastModified());//FIXME: doesnt work with wget + prob others as well
r.addHeader("ETag",f.getPath()+f.lastModified());
return r;
}
isNotModified 方法:
/**
* check if the file has been modified since the last time client requested it
* */
public boolean isNotModified(File ff,Properties header, Properties params){
if(params.getProperty("bust")!= null ||params.getProperty("cachebust")!=null)
return false;
if(ff.getName().endsWith(".pg"))
return false;
if(ff.getPath().indexOf("/api/")>=0)
return false;
if("no-cache".equalsIgnoreCase(header.getProperty("cache-control")))
return false;
String mod = header.getProperty("if-modified-since");//names are converted to lowercase fwiw
if(mod==null)//this should happen whenever browser sends no if-modified-since
return false;
try{
long l = Long.parseLong(mod);
if(ff.lastModified()<=l)
return true;
}catch(Exception ex){
ex.printStackTrace();
}
return false;
}
出于某种原因,即使标头中没有指定 If-Modified-Since (或与缓存相关的任何内容),我仍然使用(至少)Chrome 获得 304。这会导致浏览器将资源解释为空字符串并破坏内容。