看開源框架經常看到會用到URL或者URI之類的,爲什麼要熟悉這個呢?
比如說你寫一個網絡程序,需要訪問資源,資源位置信息最好封裝起來,如果使用String表示,雖然可以使用,但是感覺挺low的。你用了URI或者URL,當你想獲取這個資源位置信息的某個屬性時怎麼着也比String方便吧。
1、URI與URL的定義
URL:統一資源定位符(uniform resource location)
2、URL的語法
3、Java中對URI的操作類
@Test
public void uriTest() throws Exception{
URI uri = new URI("https://www.qiandu.com:8080/goods/index.html?username=dgh&passwd=123#j2se");
System.out.println("scheme : " + uri.getScheme());
System.out.println("SchemeSpecificPart : " + uri.getSchemeSpecificPart());
System.out.println("Authority : " + uri.getAuthority());
System.out.println("host : " + uri.getHost());
System.out.println("port : " + uri.getPort());
System.out.println("path : " + uri.getPath());
System.out.println("query : " + uri.getQuery());
System.out.println("fragment : " + uri.getFragment());
}
運行上面的代碼,然後得到如下的結果:4、Java中對URL的操作
@Test
public void urlTest() throws Exception{
URL url = new URL("https://www.qiandu.com:8080/goods/index.html?username=dgh&passwd=123#j2se");
System.out.println("URL: " + url.toString());
System.out.println("protocol: " + url.getProtocol());
System.out.println("authority: " + url.getAuthority());
System.out.println("file name: " + url.getFile());
System.out.println("host: " + url.getHost());
System.out.println("path: " + url.getPath());
System.out.println("port: " + url.getPort());
System.out.println("default port:" + url.getDefaultPort());
System.out.println("query: " + url.getQuery());
System.out.println("ref: " + url.getRef());
}
運行上面的代碼,得到以下結果:5、UserInfo屬性
sftp://[email protected]///app/index.pdf
就是在主機名前面有類似於xxx@的東西,其實這種表示就:用戶@主機名或者用戶@IP。@前面表示登錄主機的用戶,也就是UserInfo了。