[英]How to check valid URL address?
我有簡單的代碼,可以獲取網址路徑並重定向到該網址:
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
為true, wellFormed
也為true!
如何驗證網址?
對於這種情況,請使用PS HelpUrl + path = http://web-server/SomeSystemindex.html
。 其中HelpUrl是“ http:// web-server / SomeSystem ”,而path = index.html
PPS就像Martin所說的那樣-創建連接並檢查狀態碼。
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;
}
據我所知,確定地址是否有效的唯一方法是打開連接。 如果連接有效,則該地址有效。 如果不是,則連接無效。 有一些技巧可以過濾掉錯誤的URL,但是要知道地址是否有效,您需要打開一個連接。
一個例子已經發布在StackOverflow上了
或在這里:
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
這個簡單的輔助方法使用正則表達式來確保網站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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.