Reputation: 63
I have springboot application that enable http caching. I'm using webRequest.checkModifiedSince
as describe in here. When running my application in browser I get correct result, 200
status code on first hit and 304
on next hit. But when I run maven test to my application it seems that webRequest.checkModifiedSince
always return false.
Here is my testcase :
@Test
public void checkCache() throws Exception {
MvcResult res = this.mockMvc.perform(get("/resource/to/cache.jpg"))
.andExpect(status().isOk())
.andReturn();
String date = res.getResponse().getHeader("Last-Modified");
HttpHeaders headers = new HttpHeaders();
headers.setIfModifiedSince(Long.parseLong(date));
headers.setCacheControl("max-age=0");
this.mockMvc.perform(get("same/resource/as/above.jpg")
.headers(headers))
.andExpect(status().isNotModified());
}
Did I do something wrong here?
Upvotes: 4
Views: 1023
Reputation: 59076
When sending conditional HTTP requests, you should usually only send If-Modified-Since
(using the Last-Modified
value) and If-None-Match
(using the Etag
value).
In this example, you're also sending a max-age=0
directive which means "don't give me anything that's older than 0 seconds", indeed asking the server to send the response anyway (see RFC doc about max-age). This is typically the kind of directive you'd see in browser requests when doing a "hard refresh".
Remove that directive from the request and the server should respond 304 Not Modified.
Upvotes: 2
Reputation: 120761
The Last-Modified
header is a string like: Wed, 15 Nov 1995 04:58:08 GMT
. So I highly doubt that you can parse them to an Long
.
I think that your test is failing because an parse exception.
String dateString = res.getResponse().getHeader("Last-Modified");
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
Date date = format.parse(dateString);
@See: How to parse Date from HTTP Last-Modified header?
Upvotes: 1