我有文本框(多行),我希望将Web请求发送到所有链接,以检查链接是否正常工作,如果不工作,则错误消息
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;
答案 0 :(得分: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无效
答案 1 :(得分:0)
您可以使用HttpWebResponse状态:
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
if (objResponse.StatusCode == HttpStatusCode.OK)
{
// put your code when link is valid.
}
您也可以将代码放在try catch
内以捕获一些异常,例如连接失败等。