20230627 java.net.URL
介绍
- java.net.URL
- public final class URL implements java.io.Serializable
- URI 是个纯粹的语法结构,包含用来指定 Web 资源的字符串的各种组成部分
- URL 是 URI 的一个特例,它包含了用于定位 Web 资源的足够信息
URL 语法
authority 部分具有以下形式:
[user-info@]host[:port]
API
static
- setURLStreamHandlerFactory
- 设置应用程序的 URLStreamHandlerFactory
- 该方法在给定的 Java 虚拟机中最多可以调用一次
- URLStreamHandlerFactory 实例用于根据协议名称构造流协议处理器
构造器
- URL(String protocol, String host, int port, String file) throws MalformedURLException
- URL(String protocol, String host, String file) throws MalformedURLException
- URL(String protocol, String host, int port, String file, URLStreamHandler handler) throws MalformedURLException
- URL(String spec) throws MalformedURLException
- URL(URL context, String spec) throws MalformedURLException
- URL(URL context, String spec, URLStreamHandler handler) throws MalformedURLException
public
-
openConnection
URLConnection openConnection() throws java.io.IOException
- 返回一个
URLConnection
对象,该对象负责管理与资源之间的连接
-
openStream
- 打开一个用于读取资源数据的输入流
- 等同于
openConnection().getInputStream();
-
getContent
- 获取此 URL 的内容
- 不实用,可能返回流对象
- 等同于
openConnection().getContent()
-
getDefaultPort
- 获取协议的默认端口号
-
sameFile
- 比较两个 URL,不包括 fragment
-
toExternalForm
- 构造此URL的字符串表示形式
- 功能同
toString
-
toURI
- 转
URI
- 转
获取 URL 的组件
- getProtocol
- getAuthority
- getUserInfo
- getHost
- getPort
- 返回 -1 表示未定义
- getPath
- getQuery
- 查询,即URL中 ? 后面的键值对
- getFile
- 文件名
- getRef
- 锚点,即URL中 # 后面的部分
代码示例
URL url = new URL("https://www.bilibili.com/video/BV1Rj411D7Eg/?spm_id_from=333.1007.tianma.1-1-1"
+ ".click&vd_source=4a4c5fa550920bace1f35eeab12544f0");
Console.log(url);
Console.log("Protocol :: ",url.getProtocol());
Console.log("Authority :: ",url.getAuthority());
Console.log("UserInfo :: ",url.getUserInfo());
Console.log("Host :: ",url.getHost());
Console.log("Port :: ",url.getPort());
Console.log("Path :: ",url.getPath());
Console.log("Query :: ",url.getQuery());
Console.log("File :: ",url.getFile());
Console.log("Ref :: ",url.getRef());
Console.log("----------------------------------");
Console.log(url.getDefaultPort());
Console.log(url.getContent());
打印结果:
https://www.bilibili.com/video/BV1Rj411D7Eg/?spm_id_from=333.1007.tianma.1-1-1.click&vd_source=4a4c5fa550920bace1f35eeab12544f0
Protocol :: https
Authority :: www.bilibili.com
UserInfo :: null
Host :: www.bilibili.com
Port :: -1
Path :: /video/BV1Rj411D7Eg/
Query :: spm_id_from=333.1007.tianma.1-1-1.click&vd_source=4a4c5fa550920bace1f35eeab12544f0
File :: /video/BV1Rj411D7Eg/?spm_id_from=333.1007.tianma.1-1-1.click&vd_source=4a4c5fa550920bace1f35eeab12544f0
Ref :: null
----------------------------------
443
sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@7d9f158f