2011-09-15 109 views
1

我試圖用c#下載學校項目的此網頁的源代碼。
這是網頁IM試圖得到:如無法從網頁下載源代碼

HttpWebRequest request = (HttpWebRequest) 
      WebRequest.Create("http://www.epicurious.com/tools/fooddictionary/entry?id=1650"); 

,並通過使用

WebClient client = new WebClient(); 
string value = client.DownloadString("http://www.epicurious.com/tools/fooddictionary/entry?id=1650"); 


http://www.epicurious.com/tools/fooddictionary/entry?id=1650

我曾嘗試代碼並沒有方法讓我的網頁源代碼。任何幫助,將不勝感激。

+0

當你說「源」時,你的意思是HTML,對吧? –

回答

4

使用HttpWebRequest.Create

try 
{ 
    WebRequest req = HttpWebRequest.Create("http://www.epicurious.com/tools/fooddictionary/entry?id=1650"); 
    req.Method = "GET"; 

    string source; 
    using (StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream())) 
    { 
     source = reader.ReadToEnd(); 
    } 
} 
catch (Exception ex) 
{ 
    //Log the exception 
    MessageBox.Show(ex.ToString()); 
} 

使用DownloadString

WebClient client = new WebClient(); 
string reply = client.DownloadString("http://www.epicurious.com/tools/fooddictionary/entry?id=1650"); 

上述方法對我工作的罰款。檢查是否有任何..

+0

我將upvoted這個例外,你的例子使用'ex.Message'。它應該是'ex.ToString()'。 –

+0

通常我們不會向用戶顯示完整的例外,但會記錄完整的例外情況。這就是我使用exception.Message的原因。在這種情況下,我們可以顯示完整的例外以找到問題。謝謝..更新我的回答 – Damith

+0

Upvoted。我的感覺是,如果你要顯示異常處理,那麼向新手展示如何使用'ex.ToString()'。否則,認爲'ex.Message'是足夠的信息。 –

0

這個怎麼樣...

string sourceCode = ""; 
Uri site = new Uri("http://www.epicurious.com/tools/fooddictionary/entry?id=1650"); 
WebRequest request = WebRequest.Create(site); 
using(StreamReader reader = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.ASCII)){ 
    sourceCode = reader.ReadToEnd(); 
} 

「使用」的聲明將被關閉的流對您例外。注意:在流上調用close也會調用它正在使用的任何流的類,這就是爲什麼你只需要使用單個語句的原因

+0

-1:也許你可以編輯你的答案,以顯示正確使用「使用」?然後我會刪除downvote。 –

+0

@John Saunders,那怎麼樣? – musefan

+0

夠好。你應該真的打破GetResponse和GetResponseStream調用,但是這樣做。 –