[英]What's the safest way to determine if 2 URLs are the same?
如果我有URL A說http://www.example.com/
和另一個,請說http://www.example.com
。 什么是最安全的方法來確定兩者是否相同,而不查詢網頁並進行差異?
例子:
http://www.example.com/
VS http://www.example.com
(上文提到) http://www.example.com/aa/../
VS http://www.example.com
編輯:澄清:只是想根據RFC 1738標准知道URL在等效的上下文中是否相同。
在.Net中,您可以使用System.Uri類。
讓u1 =新的Uri(“ http://www.google.com/ ”);;
val u1:Uri = http://www.google.com/
讓u2 =新的Uri(“ http://www.google.com ”);;
val u2:Uri = http://www.google.com/
u1.Equals(U2);;
val it:bool = true
要進行更細粒度的比較,可以使用Uri.Compare方法。 還有靜態方法來處理Uri字符串中各種形式的字符轉義和編碼,這無疑在徹底處理主題時非常有用。
沒有請求URL,你幾乎無能為力。 但您可以定義幾個啟發式方法:
.htm
和.html
是一樣的 /base/
和/base/
/base/index.html
是相同的 url.com
和www.url.com
相同。 這完全取決於“相同”的URL究竟是什么意思。
為了讓那些不了解F#的人受益,這里有一個快速而骯臟但完整的C#控制台應用程序,它演示了如何使用Uri類來判斷兩個URL是否相同。 運行此代碼時,您應該看到兩行:“true”,后跟“false”:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(IsSameUrl("http://stackoverflow.com/", "http://stackoverflow.com").ToString());
Console.WriteLine(IsSameUrl("http://stackoverflow.com/", "http://codinghorror.com").ToString());
Console.ReadKey();
}
static bool IsSameUrl(string url1, string url2)
{
Uri u1 = new Uri(url1);
Uri u2 = new Uri(url2);
return u1.Equals(u2);
}
}
}
Yuval A答案中添加的內容很少:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.