1

嗨,我有一個程序,這就是看好如何跳過HttpWebResponse 404

for (int i=1; i < 1000; i++) 
{ 
    string id = i.ToString(); 
    string url_source = get_url_source("http://mysite.com/"+id); 
} 

和方法

public static string get_url_source(string url) 
    { 
     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 
     HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
     System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream()); 
     return sr.ReadToEnd(); 
    } 

我應該如何改變我的方法,以便主程序會直接跳過該網址一些網頁並在404-未找到時繼續下一個ID?

我改變了我的循環這個

try 
      { 
       string url_source = get_url_source(url); 
      } 
      catch(WebException ex) 
      { 
       if (ex.Status == WebExceptionStatus.ProtocolError) 
       { 
        ConsoleBox.Text += i + ": " + WebExceptionStatus.ProtocolError.ToString() + "\r\n"; 
        continue; 
       } 
       else 
       { 
        throw; 
       } 
      } 

回答

3

捕獲錯誤並檢查其狀態。如果是404 - 繼續循環,否則重新拋出它。

for (int i=1; i < 1000; i++) 
{ 
    string id = i.ToString(); 
    try 
    { 
     string url_source = get_url_source("http://mysite.com/"+id); 
    } 
    catch(WebException ex) 
    { 
     HttpWebResponse webResponse = (HttpWebResponse)ex.Response;   
     if (webResponse.StatusCode == HttpStatusCode.NotFound) 
     { 
      continue; 
     } 
     else 
     { 
      throw; 
     } 
    } 

} 
+0

謝謝我遵循你的例子,現在罰款。 – Incognito

2

你需要捕捉,當你做的GetResponseStream

try 
{ 
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 
    HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
    System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream()); 
    return sr.ReadToEnd(); 
} 
catch (WebException webEx) 
{ 
    //If you want only 404, some logic here 
    //if (((HttpWebResponse)webEx.Response).StatusCode == HttpStatusCode.NotFound) 
    //{ 
    //} 
    //else 
    //{ 
    //  throw; 
    //} 
    //webEx.Status; 
} 
+0

是的,我這樣做,但我的循環將如何知道引發異常,並跳過在下一個ID? – Incognito

+0

如果您在catch塊中沒有任何操作(吞下它),如註釋中所示,那麼您的循環將繼續。一般來說,吞嚥異常並不是很好,但我不確定你在這裏有選擇。 –

+0

或者,如果你不想吞下......解釋404異常時你想要發生什麼。 – humblelistener

0

嘗試拋出的引發WebException: 如果(response.StatusCode == HttpStatusCode。 OK)

0

使用try/catch,並將WebException用作異常類型。您可以測試狀態:

ex.Response.StatusCode==HttpStatusCode.NotFound