如何发送网络请求以检查链接是否断开 [英] how to send web request to check the link whether the link is broken or not
问题描述
我有一个文本框(多行),我想将Web请求发送到所有链接,以检查该链接是否正常(如果不正常,则显示错误消息)
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;
推荐答案
除非我误解了您,否则您可以执行以下操作:
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;
}
}
假设您在textBox1
中有以下内容:
Assuming you had in textBox1
something like this:
http://www.stackoverflow.com/
http://www.invalid-page.com/
http://www.invalid.again.com/120938213
http://www.stackoverflow.com/
http://www.invalid-page.com/
http://www.invalid.again.com/120938213
您最终将在textBox2
中获得以下文本:
You will end up with the following text in textBox2
:
链接 http://www.invalid-page.com/不起作用
链接 http://www.invalid.again.com/120938213 不起作用
Link http://www.invalid-page.com/ not working
Link http://www.invalid.again.com/120938213 not working
这篇关于如何发送网络请求以检查链接是否断开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!