我有简单的代码,获取url路径并重定向到此url:
private void Redirect(String path)
{
Uri validatedUri = null;
var result = Uri.TryCreate(HelpURL + path, UriKind.Absolute, out validatedUri);
if (result&&validatedUri!=null)
{
var wellFormed = Uri.IsWellFormedUriString(HelpURL + path, UriKind.Absolute);
if(wellFormed)
{
Response.Write("Redirect to: " + HelpURL + path);
Response.AddHeader("REFRESH", "1;URL=" + HelpURL + path);
}
else //error
{
Response.Write(String.Format("Validation Uri error!", path));
}
}
else
{
Response.Write(String.Format("Validation Uri error!", path));
}
}
网址示例:http://web-server/SomeSystemindex.html
。它不是有效的地址,但是:
我的代码result
是真的,wellFormed
也是如此!
如何验证网址?
P.S。对于这种情况,HelpUrl + path = http://web-server/SomeSystemindex.html
。 HelpUrl的位置为“http://web-server/SomeSystem”,路径= index.html
P.P.S。我像马丁所说的那样 - 创建连接并检查状态代码。
HttpWebRequest req = WebRequest.Create(HelpURL + path) as HttpWebRequest;
req.UseDefaultCredentials = true;
req.PreAuthenticate = true;
req.Credentials = CredentialCache.DefaultCredentials;
var statusCode= ((HttpWebResponse)req.GetResponse()).StatusCode;
if (statusCode == HttpStatusCode.NotFound)
isValid = false;
else if (statusCode == HttpStatusCode.Gone)
isValid = false;
else
{
isValid = true;
}
答案 0 :(得分:4)
据我所知,确定地址是否有效的唯一方法是打开连接。如果连接存在,则地址有效。如果不是,则连接无效。有一些技巧可以过滤掉错误的网址,但要知道地址是否有效,您需要打开一个连接。
已在StackOverflow here
上发布了一个示例或者在这里:
URL url;
URL wrongUrl;
try {
url = new URL("http://google.com");
wrongUrl = new URL( "http://notavalidurlihope.com");
HttpURLConnection con = (HttpURLConnection ) url.openConnection();
System.out.println(con.getResponseCode());
HttpURLConnection con2 = (HttpURLConnection ) wrongUrl.openConnection();
System.out.println(con2.getResponseCode());
} catch (IOException e) {
System.out.println("Error connecting");
}
注意:之后断开连接
输出:
200
Error connecting
答案 1 :(得分:1)
此简单的帮助程序方法使用正则表达式来确保网站URL的格式正确。如果有空格(这很重要),它也会失败。
以下URL的通行证:
google.com
www.google.com
此操作失败:
www.google.com/空格不正确/
以下是我创建的帮助方法:
public static bool ValidateUrl(string value, bool required, int minLength, int maxLength)
{
value = value.Trim();
if (required == false && value == "") return true;
if (required && value == "") return false;
Regex pattern = new Regex(@"^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$");
Match match = pattern.Match(value);
if (match.Success == false) return false;
return true;
}