简体   繁体   English

为什么此代码无法检测页面更新?

[英]Why doesn't this code work to detect a page update?

Well the question pretty much explains it. 问题很好地解释了这一点。 I'm aware the code is very dirty during String.equals, but I just wanted to see if I understood header responses. 我知道在String.equals期间代码很脏,但是我只是想看看我是否了解标头响应。 Clearly I do not, because I watch in my browser and when a new question is added, my program never outputs "Yep it changed" Why is that? 显然我没有,因为我在浏览器中观察并且添加了新问题时,我的程序从不输出“是的,它已更改”,这是为什么呢?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using System.Net;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {

            Uri myUri = new Uri("http://stackoverflow.com/questions?sort=newest");

            HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(myUri);



            HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
            string org = myHttpWebResponse.Headers.GetValues("Date")[0];
            string newone = "";

            while (true) //STRICTING FOR TESTING. THIS WOULD BE A Dos ATTACK AS IT NEVER HAS A DELAY BETWEEN REQUESTS.
            {

                myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
                newone = myHttpWebResponse.Headers.GetValues("Date")[0];

                if (!newone.Equals(org))
                    break;
            }


            Console.WriteLine("Yep it changed");
            Console.ReadLine();
        }
    }
}

Your code is checking the same HttpWebResponse , over and over. 您的代码一遍又一遍地检查相同的HttpWebResponse It's not making new requests, it's only looking at the response from the first (and only request). 它不是在发出新请求,而只是在看第一个(也是唯一一个请求)的响应。

From MSDN : MSDN

Multiple calls to GetResponse return the same response object; 多次调用GetResponse将返回相同的响应对象。 the request is not reissued. 该请求不会重新发出。

You'll have to put all of the code that makes a request inside the loop, to start the whole request/response process over again. 您必须将发出请求的所有代码放入循环中,以重新开始整个请求/响应过程。

Also note, that if you were running this code against my website, I would be pretty upset. 另请注意,如果您在我的网站上运行此代码,我会很不高兴。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM