2013-02-27 56 views
0

我有文本框(多行)從那我想發送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

你爲什麼這樣做'strLink = sr.ReadToEnd( )'? – 2013-02-27 06:18:42

+0

以結束字符串 – hitarth 2013-02-27 06:53:55

+0

的讀取,但是'strLink'將包含包含所有鏈接的大文本。首先,你不是從文本中解析每個鏈接。我最後一條評論的意思是,你將HTML文本分配給你的第一個URL返回(假設你調用了它),這個變量根本沒有意義。 – 2013-02-27 07:03:52

回答

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不工作

+0

謝謝我正在執行此代碼 – hitarth 2013-02-27 06:11:40

+0

@ user2071502請參閱我的編輯。 – 2013-02-27 06:13:26

+0

對不起兄弟不工作,因爲我想,我希望我有鏈接在textbox1的列表,並從那我想發送webrequest每個人然後檢查鏈接是否損壞或不是如果損壞然後發送特定的錯誤信息,所有將有在文本框中顯示 – hitarth 2013-02-27 06:47:10

0

您可以使用HttpWebResponse狀態波紋管:

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

你也可以把代碼中的try catch內捕捉一些例外,例如,連接故障等

+0

這將無法正常工作。如果該網站返回一個'(404)Not Found'錯誤,它將在第一行失敗。 – 2013-02-27 06:13:56

+0

yu可以放在裏面試試catch來處理異常。 – Habibillah 2013-02-27 06:16:57

+0

對不起兄弟不工作,因爲我想,我希望我有鏈接在textbox1的列表,並從那我想發送webrequest每個人然後檢查鏈接是否損壞或不是如果損壞,然後發送特定的錯誤信息,所有將有在textbox2中顯示 – hitarth 2013-02-27 06:43:01