---
# System prepended metadata

title: Http cache ETag
tags: [HTTP, Cache, ETag, Java]

---

# Http cache ETag

###### tags: `HTTP` `Cache` `Java` `ETag`

https://blog.othree.net/log/2012/12/22/cache-control-and-etag/

https://medium.com/frochu/http-caching-3382037ab06f

## 注意

因為瀏覽器通常都有會設定，accept-encoding: gzip, deflate, br
所以 If-None-Match 會帶有 W/ weak驗證的方式

Response Header
```
cache-control: max-age=0
cf-cache-status: DYNAMIC
cf-ray: 5466bc15f90cd376-LAX
content-encoding: br
content-type: application/json;charset=utf-8
date: Tue, 17 Dec 2019 06:10:35 GMT
etag: W/"b3b38875bbc3855cb49bb068befdb0a84122b97d4b66f613208a12ef5e63ec34"
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
server: cloudflare
status: 20055cb49bb068befdb0a84122b97d4b66f613208a12ef5e63ec34"
```

## java 範例

```
String eTagFromBrowser = req.getHeader("If-None-Match");
String etag = getEtag(res_arr.toString());
if (eTagFromBrowser != null && eTagFromBrowser.equals(etag)) {
    resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
    return;
}
resp.addHeader("ETag", etag);

...

public String getEtag(String str) {
    return "W/\"" + Mytools.toSHA256(str) + "\"";
}
```