Uri.IsWellFormedUriString 返回 true,但无法从 url 读取
本文关键字:url 读取 IsWellFormedUriString 返回 true Uri | 更新日期: 2023-09-27 18:37:19
我正在尝试通过以下方法检查网址http://master.dev.brandgear.net
是否有效:
private bool UrlIsValid(string url)
{
using (var webClient = new WebClient())
{
bool response;
try
{
webClient.UseDefaultCredentials = true;
using (Stream strm = webClient.OpenRead(url))
{
response = true;
}
}
catch (WebException we)
{
response = false;
}
return response;
}
}
但是,我收到一个网络异常"404 not found."
.我已经用Uri.IsWellFormedUriString
检查了 uri,它返回为 true。但是,可以通过浏览器打开相同的 URL。知道如何验证它吗?
我使用以下 URL http://master.dev.brandgear.net 运行您的示例,并且还引发了异常。如果您在浏览器中打开相同的URL(例如Firefox)并运行Firebug插件,请打开"网络"选项卡,您将看到错误404(找不到页面)。您的代码正常,但服务器返回 404。
要真正获得响应,您必须在发生 404 异常时使用 WebException 而不是 GetResponse 或 GetResponseStream 方法。在这些情况下,还可以使用 HttpWebRequest 和 HttpWebResponse 进行更好的控制,因此在异常发生后,您可以检查其状态以查看它是否是 ProtocolError,如果是,则从那里获取响应:
private bool UrlIsValid(string url)
{
bool response = false;
HttpWebResponse rep = null;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
rep = (HttpWebResponse)request.GetResponse();
}
catch (WebException we)
{
if (we.Status == WebExceptionStatus.ProtocolError)
rep = (HttpWebResponse)we.Response;
}
if (rep != null)
{
try
{
using (Stream strm = rep.GetResponseStream())
{
response = true;
}
}
catch (WebException ex)
{
//no need variable is already false if we didnt succeed.
//response = false;
}
}
return response;
}