Java URL
URL(Uniform Resource Locator)中文名為統一資源定位符,有時也被俗稱為網頁地址。表示為互聯網上的資源,如網頁或者FTP地址。
下面我們將介紹 Java 是如處理 URL 的。URL 可以分為如下幾個部分。
protocol://host:port/path?query#ref
protocols(協議)可以是 HTTP, HTTPS, FTP, 和 File。port 為端口號。path 為文件路徑及文件名。
HTTP 協議的 URL 實例如下:
http://www.cnblogs.com/toutou/
以上 URL 實例並未指定端口,因為 HTTP 協議默認的端口號為 80。
一、URL 類方法
在 java.net 包中定義了 URL 類,該類用來處理有關 URL 的內容。對於 URL 類的創建和使用,下面分別進行介紹。
java.net.URL 提供了豐富的 URL 構建方式,並可以通過 java.net.URL 來獲取資源。
序號 | 方法 | 描述 |
---|---|---|
1 | public String getPath() | 返回 URL 路徑部分。 |
2 | public String getQuery() | 返回 URL 查詢部分。 |
3 | public String getAuthority() | 獲取此 URL 的授權部分。 |
4 | public int getPort() | 返回 URL 端口部分 |
5 | public int getDefaultPort() | 返回協議的默認端口號。 |
6 | public String getProtocol() | 返回 URL 的協議 |
7 | public String getHost() | 返回 URL 的主機 |
8 | public String getFile() | 返回 URL 文件名部分 |
9 | public String getRef() | 獲取此 URL 的錨點(也稱為"引用")。 |
10 | public URLConnection openConnection() throws IOException | 打開一個 URL 連接,並運行客戶端訪問資源。 |
@Test
public void test() throws MalformedURLException {
URL url = new URL("http://www.cnblogs.com/index.html?language=cn#j2se");
# URL:http://www.cnblogs.com/index.html?language=cn#j2se
System.out.println("URL = " + url.toString());
# protocol:http
System.out.println("protocol = " + url.getProtocol());
# authority:www.cnblogs.com
System.out.println("authority = " + url.getAuthority());
# filename:/index.html?language=cn
System.out.println("filename = " + url.getFile());
# host:www.cnblogs.com
System.out.println("host = " + url.getHost());
# path:/index.html
System.out.println("path = " + url.getPath());
# port:-1
System.out.println("port = " + url.getPort());
# default port:80
System.out.println("default port = " + url.getDefaultPort());
# query:language=cn
System.out.println("query = " + url.getQuery());
# ref:j2se
System.out.println("ref = " + url.getRef());
}
getFile() 包含參數,getPath 不包含參數部分。
每天用心記錄一點點。內容也許不重要,但習慣很重要!