URL和URI的區別
阿新 • • 發佈:2021-07-24
前言
URI(Uniform Resource Identifier),統一資源識別符號,用來唯一的標識一個資源。
URL(Uniform Resource Locator),統一資源定位器,是URI的一個子集,不僅可以標識一個資源,還包含如何定位這個資源,是一種具體的URI。
語法
scheme:[//authority][/path][?query][#fragment]
主要包含5部分,以下面的URL為例
http://user1:[email protected]:8080/news/index.asp?boardID=5&ID=24618&page=1#name
- schema,對於URL來說是訪問資源的協議的名稱,對於URI來說是分配識別符號的規範的名稱,上面例子的schema為 http,表示使用的是 http 協議。
- authority,由使用者身份資訊,主機和埠號組成,例子中的authority為 user1:[email protected]:8080,使用者身份資訊為,user1:userpwd,主機為www.aspxfans.com。
- path,用於標識資源的具體路徑,例子的path為 news/index.asp
- query,用於標識資源的附加資料,例子的query為 boardID=5&ID=24618&page=1
- fragment,表示資源的特定部分,例子的fragment為 name。
我們可以通過schema來簡單判斷是否為URL,如果schema不在
ftp, http, https, gopher, mailto, news, nntp, telnet, wais, file, or prospero
這些協議中,就不是URL。
ftp://ftp.is.co.za/rfc/rfc1808.txt
https://tools.ietf.org/html/rfc3986
mailto:[email protected]
tel:+1-816-555-1212
urn:oasis:names:docbook:dtd:xml:4.1
urn:isbn:1234567890
前面3個為URL。
java中的使用
import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; public class TestUrlAndUri { public static void main(String[] args) throws IOException, URISyntaxException { System.out.println("========URL"); URL testUrl = new URL( "http://user1:[email protected]:8080/news/index.asp?boardID=5&ID=24618&page=1#name"); System.out.println(testUrl.getProtocol()); System.out.println(testUrl.getAuthority()); System.out.println(testUrl.getUserInfo()); System.out.println(testUrl.getHost()); System.out.println(testUrl.getPort()); System.out.println(testUrl.getPath()); System.out.println(testUrl.getQuery()); System.out.println(testUrl.getRef()); System.out.println("========URI"); URI testUri = testUrl.toURI(); System.out.println(testUri.getScheme()); System.out.println(testUri.getAuthority()); System.out.println(testUri.getHost()); System.out.println(testUri.getPort()); System.out.println(testUri.getPath()); System.out.println(testUri.getQuery()); System.out.println(testUri.getFragment()); } }
結果輸出為
========URL
http
user1:[email protected]:8080
user1:userpwd
www.aspxfans.com
8080
/news/index.asp
boardID=5&ID=24618&page=1
name
========URI
http
user1:[email protected]:8080
www.aspxfans.com
8080
/news/index.asp
boardID=5&ID=24618&page=1
name
和上面我們分析的結果一致。
參考
Difference between URL and URI
java中uri與url的區別_URL和URI的區別與總結
URL組成部分詳解