Java如何获取URL的部分?
Posted borter
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java如何获取URL的部分?相关的知识,希望对你有一定的参考价值。
在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());
}
}
上述代码示例将产生以下结果 -
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
获取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());
}
}
上述代码示例将产生以下结果 -
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
以上是关于Java如何获取URL的部分?的主要内容,如果未能解决你的问题,请参考以下文章