我正在下载一个 JAR 文件,并且想使用 If-Modified-Since,这样如果我不需要它我就不会得到整个文件,但出于某种原因我的 vanilla Apache (afaik) 不是'正确返回 304。
这是来自wireshark的:
GET /whatever.jar HTTP/1.1
If-Modified-Since: Sat, 04 Jan 2014 21:46:26 GMT
User-Agent: Jakarta Commons-HttpClient/3.1
Host: example.com
HTTP/1.1 200 OK
Date: Sat, 04 Jan 2014 20:32:31 GMT
Server: Apache/2.2.4 (Unix) mod_ssl/2.2.4 OpenSSL/0.9.8e DAV/2 mod_jk/1.2.26 PHP/5.3.6 SVN/1.4.4
Last-Modified: Sat, 04 Jan 2014 19:13:14 GMT
ETag: "b6c037-1ddad9f-d17a6680"
Accept-Ranges: bytes
Content-Length: 31305119
Vary: User-Agent
Content-Type: text/plain
... [bunch of bytes] ...
我不需要指定其他 header ,是吗?我是否缺少 Apache 正确读取此 header 所需的模块?
还有其他想法或建议吗?
这是我的Java代码,供引用:
File jarFile = new File(filePath);
GetMethod get = new GetMethod(downloadUrl);
Date lastModified = new Date(jarFile.lastModified());
get.setRequestHeader("If-Modified-Since", DateUtil.formatDate(lastModified));
HttpClient client = new HttpClient();
int code = client.executeMethod(get);
更新:解决方案
If-Modified-Date
需要与服务器完全匹配,我通过在下载文件上显式设置 lastModifiedDate
来实现这一点:
String serverModified = get.getResponseHeader("Last-Modified").getValue();
jarFile.setLastModified(DateUtil.parseDate(serverModified).getTime());
执行此操作后,后续调用将不会下载该文件。
最佳答案
为了使用“If-Modified-Since” header ,您必须发送与“Last-Modified” header 相同的 header 值,即 Sat, 04 Jan 2014 19:13:14 GMT
!= 2014 年 1 月 4 日星期六 21:46:26 GMT
。 Apache 不能保证文件没有被修改并且有意给定了过去的时间(可能通过版本控制回滚)。
如果需要,您可以使用 HeadMethod 在客户端检查“Last-Modified” header 。 首先 避免“获取”未修改的资源。如果“GetMethod”已被修改,那么您将使用它。
参见 RFC2616 - Section 9 ,“HTTP/1.1:方法定义”了解更多。
关于java - Apache 不遵守 If-Modified-Since,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20927290/