当HttpWebResponse无法连接到服务器/互联网时,如何在c#中显示消息框
本文关键字:消息 显示 HttpWebResponse 连接 互联网 服务器 | 更新日期: 2023-09-27 18:21:36
我是C#的新手,正在开发从Web中抓取URL的窗口应用程序。应用程序需要连接Internet才能从Internet收集URL。问题出在没有互联网连接的情况下。应用程序显示这种类型的错误。
中发生类型为"System.Net.WebException"的未处理异常System.dll附加信息:远程名称不能是已解决:"www.google.com"
问题是我写了什么代码告诉用户,并没有互联网连接。而不是显示这种类型的Bug。这是我正在处理的代码。
listBox1.Items.Clear();
StringBuilder sb = new StringBuilder();
byte[] ResultsBuffer = new byte[8192];
string SearchResults = "http://www.google.com/search?num=1000&q=" + txtKeyWords.Text.Trim();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(SearchResults);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
string tempString = null;
int count = 0;
do
{
count = resStream.Read(ResultsBuffer, 0, ResultsBuffer.Length);
if (count != 0)
{
tempString = Encoding.ASCII.GetString(ResultsBuffer, 0, count);
sb.Append(tempString);
}
}
while (count > 0);
string sbb = sb.ToString();
HtmlAgilityPack.HtmlDocument html = new HtmlAgilityPack.HtmlDocument();
html.OptionOutputAsXml = true;
html.LoadHtml(sbb);
HtmlNode doc = html.DocumentNode;
foreach (HtmlNode link in doc.SelectNodes("//a[@href]"))
{
//HtmlAttribute att = link.Attributes["href"];
string hrefValue = link.GetAttributeValue("href", string.Empty);
if (!hrefValue.ToString().ToUpper().Contains("GOOGLE") && hrefValue.ToString().Contains("/url?q=") && hrefValue.ToString().ToUpper().Contains("HTTP://"))
{
int index = hrefValue.IndexOf("&");
if (index > 0)
{
hrefValue = hrefValue.Substring(0, index);
listBox1.Items.Add(hrefValue.Replace("/url?q=", ""));
}
}
}
您可以这样做:
//Include everything that could possibly throw an exception in the try brackets
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(SearchResults);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
}
catch (Exception e) // Here we are catching your bug-the unhandled exception
{
MessageBox.Show("You do not have an internet connection");
}
这就是为什么我的答案不完整,需要你做更多的工作:除了没有互联网,还有更多的例外。这次尝试接球将把他们全部接住。您需要找到每一个可能的异常并进行相应的处理。
首先尝试根据您的错误捕获特殊异常,然后对可能发生的任何其他错误进行一般捕获,查看此
try
{
//your code here
}
catch (WebException ex)
{
MessageBox.Show("No internet available");
}
catch (Exception ex)
{
MessageBox.Show("Error has occured");
}