how to send web request to check the link whether

2019-09-09 10:13发布

问题:

i am having text box(multi line) from that i want to send the web request to all links to check whether the link is working or not if not working then message of error

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;

回答1:

Unless I misunderstood you, you can do something like this:

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;
    }
}

Assuming you had in textBox1 something like this:

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

You will end up with the following text in textBox2:

Link http://www.invalid-page.com/ not working
Link http://www.invalid.again.com/120938213 not working



回答2:

You can use HttpWebResponse status as bellow:

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

You can also put the code inside the try catch to catch some exception e.g connection failure, etc.