在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 = "http://www.yiibai.com/javaexamples/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());
}
}
Java
上述代码示例将产生以下结果 -
URL is http://www.yiibai.com/javaexamples/index.html
protocol is http
file name is /javaexamples/index.html
host is www.yiibai.com
path is /javaexamples/index.html
port is -1
default port is 80
Shell
获取URL的一部分的另一个示例 -
package com.yiibai;
import java.net.URL;
public class PartsOfURL2 {
public static void main(String args[]) throws Exception {
URL u = new URL("http://www.yiibai.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());
}
}
Java
上述代码示例将产生以下结果 -
The URL is http://www.yiibai.com
The file part is
host is www.yiibai.com
path is
port is -1
default port is 80
原文地址:https://www.cnblogs.com/borter/p/9617171.html
时间: 2024-11-06 21:31:11