如何继续应用程序时,它得到错误404或超时

本文关键字:错误 超时 何继续 继续 应用程序 | 更新日期: 2023-09-27 17:50:35

是否有任何方法使代码仍然继续,即使它得到超时或404错误....HttpWebRequest和HttpWebResponse案例:

这里是我的代码:

string argumentTest = textBox1.text.Trim(); 
string[] lines = textBox1.Text.Split(new string[] { "'r'n", "'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;
        }

如何继续应用程序时,它得到错误404或超时

你可以使用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;
}