0

有没有办法让代码即使超时或 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;
        }
4

1 回答 1

1

您可以使用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;
}
于 2013-01-04T10:28:16.487 回答