我试图使用c#为学校项目下载此网页的源代码
这是我试图得到的页面:
http://www.epicurious.com/tools/fooddictionary/entry?id=1650
我尝试过像
这样的代码 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");
这两种方法都没有让我获得页面来源。任何帮助将不胜感激。
答案 0 :(得分: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");
以上方法对我来说很好。检查异常,如果有..
答案 1 :(得分: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();
}
“using”语句将为您关闭流。注意:在流上调用close也会调用它正在使用的任何流上的类,这就是为什么你只需要单个using语句