c# – 如果图像较新,如何从HTTP下载图像?

前端之家收集整理的这篇文章主要介绍了c# – 如果图像较新,如何从HTTP下载图像?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想实现以下功能

> C#客户端连接到HTTP服务器并将映像下载到磁盘.
>下次客户端开始检查服务器上的映像是否比磁盘上的映像更新,在这种情况下,客户端会覆盖磁盘上的映像.

对我来说,下载图像很容易,但我不知道如何检查服务器上的图像是否更新.我怎么能实现它?我想我可以检查时间戳或图像大小(或两者),但我不知道该怎么做.

解决方法

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- *标题反映了不同的响应).虽然有些实现很麻烦(没有特定调整的web-farm上的IIS6,带有mod-gzip的Apache),因此值得拿出与电子标签相关的代码并按日期进行操作.

编辑:如果你想进一步实现HTTP缓存,你也可以存储expires和max-age(如果它们都存在则使用后者并且它不同于前者)并且如果它早于那些,则完全跳过下载价值观建议.我已经完成了这个并且运行良好(我有一个内存缓存的对象由各种URI返回的XML创建,如果XML是新的或没有更改,我重新使用了对象),但是它可能与您的需求无关(如果您想要比服务器建议的更新鲜,或者如果您总是在那个窗口之外).

猜你在找的C#相关文章