ETag使用
程序员文章站
2024-02-28 18:23:40
...
关于ETag相关知识:
https://blog.csdn.net/kikikind/article/details/6266101
https://blog.csdn.net/jkxiaoxing/article/details/51499894
具体代码:
String clientEtag = request.getHeader("If-None-Match");
if (md5.equals(clientEtag)) {
response.setHeader("If-None-Match", "false");
response.setStatus(304);
return this.buildResult(RequestCode.success,"图片下载成功");
}
String contextType = "image/" + contentType;
response.setHeader("content-type", contextType);
response.setContentType(contextType);
response.setHeader("ETag", md5);
response.setHeader("If-None-Match", "true");
OutputStream outputStream = response.getOutputStream();
this.readStream(outputStream, inputStream);
md5为文件摘要,第一次加载图片时,将md5放入header的ETag中,并将header的If-None-Match设置为true
浏览器会将当前资源的ETag保存,并于下次请求时,加入If-None-Match中。请求接口时,判断If-None-Match的值是否和md5相同,如果相同则代表已经加载过,且未曾变更资源,将If-None-Match设置为false且将status设置为304即可。