[英]Why doesn't this code work to detect a page update?
問題很好地解釋了這一點。 我知道在String.equals期間代碼很臟,但是我只是想看看我是否了解標頭響應。 顯然我沒有,因為我在瀏覽器中觀察並且添加了新問題時,我的程序從不輸出“是的,它已更改”,這是為什么呢?
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();
}
}
}
您的代碼一遍又一遍地檢查相同的HttpWebResponse
。 它不是在發出新請求,而只是在看第一個(也是唯一一個請求)的響應。
從MSDN :
多次調用GetResponse將返回相同的響應對象。 該請求不會重新發出。
您必須將發出請求的所有代碼放入循環中,以重新開始整個請求/響應過程。
另請注意,如果您在我的網站上運行此代碼,我會很不高興。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.