Java URL

Java URL

URL(Uniform Resource Locator)中文名为统一资源定位符,有时也被俗称为网页地址。表示为互联网上的资源,如网页或者FTP地址。

下面我们将介绍 Java 是如处理 URL 的。URL 可以分为如下几个部分。

protocol://host:port/path?query#ref

protocols(协议)可以是 HTTP, HTTPS, FTP, 和 File。port 为端口号。path 为文件路径及文件名。

HTTP 协议的 URL 实例如下:

http://www.cnblogs.com/toutou/

以上 URL 实例并未指定端口,因为 HTTP 协议默认的端口号为 80。

一、URL 类方法

在 java.net 包中定义了 URL 类,该类用来处理有关 URL 的内容。对于 URL 类的创建和使用,下面分别进行介绍。

java.net.URL 提供了丰富的 URL 构建方式,并可以通过 java.net.URL 来获取资源。

序号 方法 描述
1 public String getPath() 返回 URL 路径部分。
2 public String getQuery() 返回 URL 查询部分。
3 public String getAuthority() 获取此 URL 的授权部分。
4 public int getPort() 返回 URL 端口部分
5 public int getDefaultPort() 返回协议的默认端口号。
6 public String getProtocol() 返回 URL 的协议
7 public String getHost() 返回 URL 的主机
8 public String getFile() 返回 URL 文件名部分
9 public String getRef() 获取此 URL 的锚点(也称为"引用")。
10 public URLConnection openConnection() throws IOException 打开一个 URL 连接,并运行客户端访问资源。
@Test
public void test() throws MalformedURLException {
    URL url = new URL("http://www.cnblogs.com/index.html?language=cn#j2se");
    # URL:http://www.cnblogs.com/index.html?language=cn#j2se
    System.out.println("URL = " + url.toString());
    # protocol:http
    System.out.println("protocol = " + url.getProtocol());
    # authority:www.cnblogs.com
    System.out.println("authority = " + url.getAuthority());
    # filename:/index.html?language=cn
    System.out.println("filename = " + url.getFile());
    # host:www.cnblogs.com
    System.out.println("host = " + url.getHost());
    # path:/index.html
    System.out.println("path = " + url.getPath());
    # port:-1
    System.out.println("port = " + url.getPort());
    # default port:80
    System.out.println("default port = " + url.getDefaultPort());
    # query:language=cn
    System.out.println("query = " + url.getQuery());
    # ref:j2se
    System.out.println("ref = " + url.getRef());
}

getFile() 包含参数,getPath 不包含参数部分。


每天用心记录一点点。内容也许不重要,但习惯很重要!

原文地址:https://www.cnblogs.com/binarylei/p/9170267.html