【发布时间】:2014-12-11 04:19:59
【问题描述】:
此代码必须根据页码找到有效页面。这应该实现逻辑 - 如果地址为http://hostname/page/x 的页面返回 OK 状态,则 url 有效,如果响应状态 NotFound,则 urls 无效。我想在 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();
}
【问题讨论】:
标签: c# try-catch http-status-codes