嗨,我有一个正在查看某些页面的程序
for (int i=1; i < 1000; i++)
{
string id = i.ToString();
string url_source = get_url_source("http://mysite.com/"+id);
}
和一个方法
public static string get_url_source(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
return sr.ReadToEnd();
}
我应该如何更改我的方法,以便在发生 404-notfound 时主程序将跳过该 url 并继续到下一个 id?
我把我的循环改成了这个
try
{
string url_source = get_url_source(url);
}
catch(WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
ConsoleBox.Text += i + ": " + WebExceptionStatus.ProtocolError.ToString() + "\r\n";
continue;
}
else
{
throw;
}
}