2011-09-15 111 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调用,但是这样做。 –