是否有任何方法使代码仍然继续,即使它得到超时或404错误....HttpWebRequest和HttpWebResponse案例:
这里是我的代码:
string argumentTest = textBox1.text.Trim();
string[] lines = textBox1.Text.Split(new string[] { "rn", "n" }, StringSplitOptions.None);
string newLine = ((char)13).ToString() + ((char)10).ToString();
foreach (string vr in lines)
{
string sourceCode = getSourceCode(vr);
if (sourceCode != null)
{
//if this code is up
} else {
//if this code is down
}
}
public static string getSourceCode(string url)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.ContentType = "text/html; charset=ISO-8859-15";
//ERROR in here 404 or timeout
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(resp.GetResponseStream());
string sourceCode = sr.ReadToEnd();
sr.Close();
resp.Close();
return sourceCode;
}
你可以使用try-catch块处理异常,如果你必须清理任何分配的资源,你可以使用finally块,它将在两种情况下执行。
public static string getSourceCode(string url)
{
string sourceCode = string.Empty;
try
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.ContentType = "text/html; charset=ISO-8859-15";
//ERROR in here 404 or timeout
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(resp.GetResponseStream());
sourceCode = sr.ReadToEnd();
sr.Close();
resp.Close();
}
catch(Exception ex){}
return sourceCode;
}