使用Http Head方法获取文件长度

来源:互联网 发布:jd抢购软件 编辑:程序博客网 时间:2024/05/16 10:42

需求

有一个固定URL的文件,服务器端程序会定期的更新这个文件,现在需要写一个工具来监控这个文件的变化。

 

解决办法

最初我想到的是把这个文件下载下来,然后通过大小来判断文件是否改变(已知该文件变化时大小会变化)。

但是这个文件有时会很大,如果每次都下载下来会消耗一定的时间,希望能更快一些。

 

搜索了一下,发现Http除了Get和Post方法外,还有Head方法,它可以获取http头信息,其中的Content-Length就是文件的大小。

 

理论

在HttpWebRequest 中设置Method属性为Head,就可以只获取http的头信息,而不返回实际内容。

除了Get,Post,Head外,Method属性还可以设置:

Method 属性设置为任何 HTTP 1.1 协议谓词:GET、HEAD、POST、PUT、DELETE、TRACE 或 OPTIONS。

在Http协议中,Head方法得到的响应和Get方法相比,除了没有正文内容以外,其它都是一样的。也就是说:

Get:http头信息+内容

Head:http头信息

这样如果我们只关心http头,而不需要内容时,就可以使用Head方法了。

 

实践

static void Main(string[] args){    var url = "http://www.google.com/intl/en_ALL/images/srpr/logo1w.png";    var len = GetHttpLength(url);    Console.WriteLine("Url:{0}\r\nLength:{1}", url,len);}static long GetHttpLength(string url){    var length = 0l;    try    {        var req = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));        req.Method = "HEAD";         req.Timeout = 5000;         var res = (HttpWebResponse)req.GetResponse();        if (res.StatusCode == HttpStatusCode.OK)        {            length =  res.ContentLength;          }        res.Close();        return length;    }     catch (WebException wex)    {        return 0;    }}

执行后输出如下:

Url:http://www.google.com/intl/en_ALL/images/srpr/logo1w.png 
Length:6803

 

注意Head方法和Get方法一样,有时候服务端设置了缓存的话会返回同样的内容回来。这时候可以在url后面增加一个时间参数使缓存失效实现实时获取.

 

参考资料

HttpWebRequest.Method 属性

中文:http://msdn.microsoft.com/zh-cn/library/90k2e0f0(v=VS.90).aspx

英文:http://msdn.microsoft.com/en-us/library/90k2e0f0(v=VS.90).aspx

Http协议中head部分

http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html


=============================

9.4 HEAD

The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself.This method is often used for testing hypertext links for validity, accessibility, and recent modification.

The response to a HEAD request MAY be cacheable in the sense that the information contained in the response MAY be used to update a previously cached entity from that resource. If the new field values indicate that the cached entity differs from the current entity (as would be indicated by a change in Content-Length, Content-MD5, ETag or Last-Modified), then the cache MUST treat the cache entry as stale.


=========================

static long GetHttpLength(string url)
        {
            var length = 0l;
            try
            {
                var req = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
                req.Method = "head";
                req.Timeout = 5000;
                var res = (HttpWebResponse)req.GetResponse();//获取响应
                if (res.StatusCode == HttpStatusCode.OK)
                {
                    StringBuilder rStr = new StringBuilder();
                    var streamReader = new StreamReader(res.GetResponseStream(), Encoding.Default);//获取响应流
                    rStr.Append(streamReader.ReadToEnd());
                    streamReader.Close();


                    length = res.ContentLength;
                }


                res.Close();
                return length;
            }
            catch (WebException wex)
            {
                return 0;
            }
        }


0 0
原创粉丝点击