当我使用Web请求和Web响应方法检查URL时。
bool result = false;
try
{
if (!url.Contains("http://")) url = "http://" + url;
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "HEAD";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{ if (response.StatusCode == HttpStatusCode.OK) result = true; }
}
catch
{
return result;
}
return result;
但是,当我查看此网址时," http://payments.rctrustee.org/"我收到了错误。所以我得到的结果是假的。但我检查浏览器这个URL是否正常工作。
我需要这个结果为真;我怎样才能改变我的代码。
答案 0 :(得分:0)
使用以下代码检查:
try
{
if (!url.Contains("http://")) url = "http://" + url;
WebRequest req = WebRequest.Create(url);
WebResponse res = req.GetResponse();
Console.WriteLine("Url Exists");
}
catch (WebException ex)
{
Console.WriteLine(ex.Message);
if (ex.Message.Contains("remote name could not be resolved"))
{
Console.WriteLine("Url is Invalid");
}
}