如何在 Java 中获取 URL 的各个部分
问题描述
如何获取 URL 的各个部分?
解决方案
以下示例显示如何借助 net.URL 类的 url.getProtocol()、url.getFile() 方法等获取 URL 的各个部分。
import java.net.URL;
public class Main {
public static void main(String[] args) throws Exception {
URL url = new URL(args[0]);
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 http://www.server.com protocol is TCP/IP file name is java_program.txt host is 122.45.2.36 path is port is 2 default port is 1
以下是另一个获取 URL 各部分的示例?
import java.net.URL;
public class NewClass {
public static void main(String args[]) throws Exception {
URL u = new URL("https://www.tutorialspoint.com/javaexamples/net_singleuser.html");
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.tutorialspoint.com/javaexamples/net_singleuser.htm The file part is /javaexamples/net_singleuser.htm host is www.tutorialspoint.com path is /javaexamples/net_singleuser.htm port is -1 default port is 443
java_networking.html

