此代碼必須根據頁碼找到有效的頁面。這應該實現邏輯 - 如果帶有地址http://hostname/page/x
的頁面返回OK狀態,則url有效,如果響應狀態NotFound,url無效。我想在內部處理HttpStatusCode,但它總是被try/catch塊捕獲。在if語句中處理HttpStatusCode,而不是try/catch
public void GetAllLinks()
{
const string baselink = "http://buzzon.khaleejtimes.com/ad-category/real-estate/page/";
//Check if OK status answer from server, page link is valid
for (int i = 1; i < 10000; i++)
{
var url = baselink + i;
if (LinkExist(url) != true)
{
try {
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
// Sends the HttpWebRequest and waits for a response.
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
if (myHttpWebResponse.StatusCode == HttpStatusCode.NotFound)
{
//Exit loop if status 404.
break;
}
WriteUrl(url);
myHttpWebResponse.Close();
}
catch (Exception ex) {
throw new Exception(ex.Message);
}
}
ParsePages();
}
謝謝。讓我嘗試。 – 2014-12-11 04:50:33
不幸的是,同樣的問題再次 - 404代碼抓住try/catch而不是如果循環。 – 2014-12-11 05:12:46
異常中沒有響應方法。你能再次檢查你的代碼嗎? – 2014-12-11 05:26:59