Java如何獲取URL的部分?

2019-10-16 22:28:03

在Java程式設計中,如何獲取URL的一部分?

以下範例顯示了如何通過net.URL類的url.getProtocol()url.getFile()方法等獲取URL的部分。

package com.yiibai;

import java.net.URL;

public class PartsOfURL {
    public static void main(String[] args) throws Exception {
        String webUrl = "/20/206/8011.htmlexamples/index.html";
        URL url = new URL(webUrl);
        System.out.println("URL is " + url.toString());
        System.out.println("protocol is " + url.getProtocol());
        System.out.println("file name is " + url.getFile());
        System.out.println("host is " + url.getHost());
        System.out.println("path is " + url.getPath());
        System.out.println("port is " + url.getPort());
        System.out.println("default port is " + url.getDefaultPort());
    }
}

上述程式碼範例將產生以下結果 -

URL is /20/206/8011.htmlexamples/index.html
protocol is http
file name is /javaexamples/index.html
host is www.tw511.com
path is /javaexamples/index.html
port is -1
default port is 80

獲取URL的一部分的另一個範例 -

package com.yiibai;

import java.net.URL;

public class PartsOfURL2 {
   public static void main(String args[]) throws Exception {
      URL u = new URL("https://www.tw511.com");
      System.out.println("The URL is " + u);
      System.out.println("The file part is " + u.getFile());
      System.out.println("host is " + u.getHost());
      System.out.println("path is " + u.getPath());
      System.out.println("port is " + u.getPort());
      System.out.println("default port is " + u.getDefaultPort());
   }
}

上述程式碼範例將產生以下結果 -

The URL is https://www.tw511.com
The file part is 
host is www.tw511.com
path is 
port is -1
default port is 80