前言

URI(Uniform Resource Identifier),统一资源标识符,用来唯一的标识一个资源。

URL(Uniform Resource Locator),统一资源定位器,是URI的一个子集,不仅可以标识一个资源,还包含如何定位这个资源,是一种具体的URI。

语法

scheme:[//authority][/path][?query][#fragment]


主要包含5部分,以下面的URL为例

http://user1:userpwd@www.aspxfans.com:8080/news/index.asp?boardID=5&ID=24618&page=1#name


  • schema,对于URL来说是访问资源的协议的名称,对于URI来说是分配标识符的规范的名称,上面例子的schema为 http,表示使用的是 http 协议。
  • authority,由用户身份信息,主机和端口号组成,例子中的authority为 user1:userpwd@www.aspxfans.com: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:john@doe.com

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:userpwd@www.aspxfans.com: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:userpwd@www.aspxfans.com:8080
user1:userpwd
www.aspxfans.com
8080
/news/index.asp
boardID=5&ID=24618&page=1
name
========URI
http
user1:userpwd@www.aspxfans.com:8080
www.aspxfans.com
8080
/news/index.asp
boardID=5&ID=24618&page=1
name


和上面我们分析的结果一致。

​​