如何使用webrequest创建循环以检查响应中的更改

时间:2017-02-01 19:14:53

标签: c# loops response webrequest

我今天问你如何制作类似浏览器的请求,简而言之我想向网站发出网页请求,让它保持活着,以便我可以在循环中检查cookie和源代码的变化吗? / p>

这是我的实际代码:

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/test.php");
        request.CookieContainer = new CookieContainer(); // needed to keep the session alive

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        string value = null;

        if (response.StatusCode == HttpStatusCode.OK)
        {
            bool search = true;

            while(search == true)
            {
                for(int i = 0; i < response.Cookies.Count && search; i++)
                {
                    if (response.Cookies[i].Name == "test")
                    {
                        value = response.Cookies[i].Value;
                        search = false;
                    }
                }
            }
        }

        if (value != null)
            Console.WriteLine("found cookie : {0}", value);

        response.Close();

提前谢谢!

1 个答案:

答案 0 :(得分:0)

只需将整个代码包装在一个循环中,然后删除已有的while循环。 如果要通过获取整个流并在某处存储或散列哈希来检查响应之间的差异,然后将其与下一个响应进行比较。 还要记得放一个try / catch,默认情况下只允许两个请求,除非你调整配置

bool search = true;

while (search == true) {
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/test.php");
    request.CookieContainer = new CookieContainer(); // needed to keep the session alive

    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    string value = null;

    if (response.StatusCode == HttpStatusCode.OK)
    {           
        for (int i = 0; i < response.Cookies.Count && search; i++)
        {
            if (response.Cookies[i].Name == "test")
            {
                value = response.Cookies[i].Value;
                search = false;
            }
        }            
    }

    if (value != null)
    {
        Console.WriteLine("found cookie : {0}", value);
    }
    response.Close();
}