我正在编写一个应用程序来抓取我的网站以获取关键字。我遇到了一个问题,如果我尝试阅读一个没有通过的页面,我会得到404(不是问题)。
但是,当我的应用程序遇到 404 web 异常时,它不会继续。我知道我需要尝试和捕获,但我不太清楚如何正确添加 404 webexception 捕获而不会出错。这是有问题的代码片段:我认为我的问题是我不知道在哪里正确放置 try/catch,因为我有返回源;我得到一个错误,当我添加一个 catch 时它没有返回一个值。
string url = string.Format(@"http://127.0.0.1/website/" + searchterm);
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Method = "GET";
req.UserAgent = "MoZilla/5.0 (Windows; U; MSIE 9.0; WIndows NT 9.0; en-US))";
Uri target = req.RequestUri;
string source;
using (StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream()))
{
source = reader.ReadToEnd();
}
return source;