我想实现以下功能:
AC# 客户端连接到 HTTP 服务器并将图像下载到磁盘。
下次客户端启动时会检查服务器上的图像是否比磁盘上的图像新,在这种情况下,客户端会覆盖磁盘上的图像。
对我来说,下载图像很容易,但我不确定如何检查服务器上的图像是否更新。我怎么能实现它?我想我可以检查时间戳或图像大小(或两者),但我不知道该怎么做。
尝试If-Modified-Since
请求字段。http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
我不确定每个服务器都完全支持它。因此,如果不支持它并且您仍然会获得文件(如果支持则不是 304),您可以计算校验和,如果它们不同,请考虑修改文件。或者只是覆盖 - 你将永远拥有最新版本。
HttpWebRequest 可以只使用 IE 缓存,所以如果所有图像都将在该缓存中,并且重写文件(但不必下载)的成本是可以接受的,您可以使用它。
如果您需要自己处理,那么:
鉴于:
string uri; //URI of the image.
DateTime? lastMod; // lastModification date of image previously recorded. Null if not known yet.
string eTag; //eTag of image previously recorded. Null if not known yet.
您必须在最后存储这些,并在开始时再次检索它们(当不是新图像时)。这取决于你,因为剩下的工作:
var req = (HttpWebRequest)WebRequest.Create(uri);
if(lastMod.HasValue)
req.IfModifiedSince = lastMod.Value;//note: must be UTC, use lastMod.Value.ToUniversalTime() if you store it somewhere that converts to localtime, like SQLServer does.
if(eTag != null)
req.AddHeader("If-None-Match", eTag);
try
{
using(var rsp = (HttpWebResponse)req.GetResponse())
{
lastMod = rsp.LastModified;
if(lastMod.Year == 1)//wasn't sent. We're just going to have to download the whole thing next time to be sure.
lastMod = null;
eTag = rsp.GetResponseHeader("ETag");//will be null if absent.
using(var stm = rsp.GetResponseStream())
{
//your code to save the stream here.
}
}
}
catch(WebException we)
{
var hrsp = we.Response as HttpWebResponse;
if(hrsp != null && hrsp.StatusCode == HttpStatusCode.NotModified)
{
//unfortunately, 304 when dealt with directly (rather than letting
//the IE cache be used automatically), is treated as an error. Which is a bit of
//a nuisance, but manageable. Note that if we weren't doing this manually,
//304s would be disguised to look like 200s to our code.
//update these, because possibly only one of them was the same.
lastMod = hrsp.LastModified;
if(lastMod.Year == 1)//wasn't sent.
lastMod = null;
eTag = hrsp.GetResponseHeader("ETag");//will be null if absent.
}
else //some other exception happened!
throw; //or other handling of your choosing
}
正确实施时,电子标签比上次修改的更可靠(注意更改的亚秒级分辨率,并反映由于不同的 Accept-* 标头而导致的不同响应)。虽然有些实现是错误的(没有特别调整的网络场上的 IIS6,带有 mod-gzip 的 Apache),因此值得取出与电子标签相关的代码并按日期进行。
编辑:如果您想进一步实现 HTTP 缓存,您还可以存储 expires 和 max-age (如果它们都存在并且不同意前者,则使用后者)并完全跳过下载,如果它早于那些值建议。我已经这样做了并且效果很好(我有一个由各种 URI 返回的 XML 创建的对象的内存缓存,如果 XML 是新的或没有更改,我会重新使用该对象),但是它可能与您的需求无关(如果您希望比服务器建议的更新鲜,或者如果您总是在那个窗口之外)。
您需要阅读RFC 2616和相关 RFC(在http://www.rfc-editor.org/cgi-bin/rfcsearch.pl搜索 1616 )。特别值得一提的是,第 13 节,HTTP 中的缓存,第 47-62 页。然后阅读相关的请求/响应标头和您可能会返回的相关状态代码。
HttpWebRequest
您可以通过和HttpWebResponse
类访问所有标题和状态值。
但是应该注意,您可以向服务器询问您想要的任何内容:最终是服务器决定是否向您发送该 URI 的新表示。您可能希望使用 HTTPHEAD
动词而不是其GET
动词来向服务器询问资源。
HEAD 方法与 GET 相同,只是服务器不能在响应中返回消息体。响应 HEAD 请求的 HTTP 标头中包含的元信息应该与响应 GET 请求发送的信息相同。此方法可用于获取有关请求所隐含的实体的元信息,而无需传输实体主体本身。这种方法通常用于测试超文本链接的有效性、可访问性和最近的修改。