欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

使用Http状态码来验证网页内容是否有更新

最编程 2024-08-13 20:08:15
...
        static void Main(string[] args)
        {
            
string url = "http://www.stats.gov.cn/top.html";

            
// 检查3天前网页是否发生了变化
            DateTime modifiedSince = DateTime.Now.AddDays(-3);
            
// 输出false
            Console.WriteLine(PageHasChanged(url, modifiedSince));

            
// 检查3个月前是否发生了变化
            modifiedSince = DateTime.Now.AddMonths(-3);
            
// 输出true
            Console.WriteLine(PageHasChanged(url, modifiedSince));
        }

        
private static bool PageHasChanged(string url, DateTime modifiedSince)
        {
            
bool changed = false;

            
// 设置请求信息
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            
// 最关键的一项设置 将请求的IfModifiedSince设置为指定的时间
            request.IfModifiedSince = modifiedSince;

            HttpWebResponse response 
= null;
            
try
            {
                response 
= request.GetResponse() as HttpWebResponse;

                
// 根据返回的状态码判断内容是否发生了变化 
                
// 200表示页面发生了变化
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    changed 
= true;
                }
                
else if (response.StatusCode == HttpStatusCode.NotModified)
                {
                    changed 
= false;
                }

                response.Close();
            }
            
catch (WebException ex)
            {
                
// 对于没有发生变化的页面 通常会通过抛出异常的方式提示页面未发生变化
                if ((ex.Response as HttpWebResponse).StatusCode == HttpStatusCode.NotModified)
                {
                    changed 
= false;
                }
                
else
                {
                    
throw ex;
                }
            }

            
return changed;
        }

推荐阅读