0

我有文本框(多行),我想将网络请求发送到所有链接以检查链接是否有效,如果不工作则错误消息

string strLink = TextBox1.Text;
WebResponse objResponse;
WebRequest objRequest = System.Net.HttpWebRequest.Create(strLink);

objResponse = objRequest.GetResponse();
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
    strLink = sr.ReadToEnd();
    sr.Close();
}
strLink = strLink.Replace("<form id='form1' method='post' action=''>", "");
strLink = strLink.Replace("</form>", "");
//strResult = strResult.Replace("<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" /><html xmlns="http://www.w3.org/1999/xhtml">");
div.InnerHtml = TextBox1.Text;
4

2 回答 2

3

除非我误解了你,否则你可以这样做:

var links = textBox1.Text.Split(new string[] { "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var link in links) {
    if (!IsLinkWorking(link)) {
        //Here you can show the error. You don't specify how you want to show it.
        textBox2.Text += string.Format("Link {0} not working\n", link);
    }
}

bool IsLinkWorking(string url) {
    HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(url);

    //You can set some parameters in the "request" object...
    request.AllowAutoRedirect = true;

    try {
        HttpWebResponse response = (HttpWebResponse) request.GetResponse();
        return true;
    } catch { //TODO: Check for the right exception here
        return false;
    }
}

假设你有这样的textBox1事情:

http://www.stackoverflow.com/
http://www.invalid-page.com/
http://www.invalid.again.com/120938213

您将在以下文本中结束textBox2

链接http://www.invalid-page.com/不起作用
链接http://www.invalid.again.com/120938213不起作用

于 2013-02-27T06:08:17.127 回答
0

您可以使用 HttpWebResponse 状态如下:

HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
if (objResponse.StatusCode == HttpStatusCode.OK)
{
   // put your code when link is valid.
}

您还可以将代码放入其中try catch以捕获一些异常,例如连接失败等。

于 2013-02-27T06:09:33.690 回答