Java URL 类
URL (Uniform Resource Locator) 是统一资源定位符的缩写,用于在互联网上定位资源。在 Java 中,java.net.URL
类提供了处理 URL 的功能,允许开发者创建 URL 对象、解析 URL 组成部分以及建立网络连接。
URL 类的基本结构
一个标准的 URL 通常由以下几部分组成:
protocol://host:port/path?query#fragment
例如:
https://www.example.com:8080/products?id=123#details
主要组成部分
- 协议(Protocol):https
- 主机(Host):www.example.com
- 端口(Port):8080
- 路径(Path):/products
- 查询参数(Query):id=123
- 片段(Fragment):details
创建 URL 对象
Java 提供了多种构造方法来创建 URL 对象:
1. 使用完整 URL 字符串
实例
try {
URL url = new URL("https://www.example.com");
} catch (MalformedURLException e) {
e.printStackTrace();
}
URL url = new URL("https://www.example.com");
} catch (MalformedURLException e) {
e.printStackTrace();
}
2. 分别指定协议、主机和文件
实例
try {
URL url = new URL("https", "www.example.com", "/index.html");
} catch (MalformedURLException e) {
e.printStackTrace();
}
URL url = new URL("https", "www.example.com", "/index.html");
} catch (MalformedURLException e) {
e.printStackTrace();
}
3. 指定协议、主机、端口和文件
实例
try {
URL url = new URL("https", "www.example.com", 8080, "/api/data");
} catch (MalformedURLException e) {
e.printStackTrace();
}
URL url = new URL("https", "www.example.com", 8080, "/api/data");
} catch (MalformedURLException e) {
e.printStackTrace();
}
URL 类的常用方法
获取 URL 各部分信息
实例
URL url = new URL("https://www.example.com:8080/products?id=123#details");
System.out.println("协议: " + url.getProtocol()); // https
System.out.println("主机: " + url.getHost()); // www.example.com
System.out.println("端口: " + url.getPort()); // 8080
System.out.println("路径: " + url.getPath()); // /products
System.out.println("查询: " + url.getQuery()); // id=123
System.out.println("片段: " + url.getRef()); // details
System.out.println("协议: " + url.getProtocol()); // https
System.out.println("主机: " + url.getHost()); // www.example.com
System.out.println("端口: " + url.getPort()); // 8080
System.out.println("路径: " + url.getPath()); // /products
System.out.println("查询: " + url.getQuery()); // id=123
System.out.println("片段: " + url.getRef()); // details
打开网络连接
URL 类提供了几种打开网络连接的方法:
- openConnection():返回一个 URLConnection 对象
- openStream():打开输入流,用于读取数据
实例
// 使用 openStream() 读取网页内容
try (InputStream in = url.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
try (InputStream in = url.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
URL 编码与解码
在 URL 中,某些字符需要被编码(如空格、中文等)。Java 提供了 URLEncoder 和 URLDecoder 类来处理编码和解码。
URL 编码示例
实例
String query = "name=张三&age=25";
String encodedQuery = URLEncoder.encode(query, "UTF-8");
System.out.println(encodedQuery); // 输出: name%3D%E5%BC%A0%E4%B8%89%26age%3D25
String encodedQuery = URLEncoder.encode(query, "UTF-8");
System.out.println(encodedQuery); // 输出: name%3D%E5%BC%A0%E4%B8%89%26age%3D25
URL 解码示例
实例
String decodedQuery = URLDecoder.decode(encodedQuery, "UTF-8");
System.out.println(decodedQuery); // 输出: name=张三&age=25
System.out.println(decodedQuery); // 输出: name=张三&age=25
实际应用示例
示例 1:下载文件
实例
URL fileUrl = new URL("https://example.com/files/sample.pdf");
try (InputStream in = fileUrl.openStream();
FileOutputStream out = new FileOutputStream("sample.pdf")) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
System.out.println("文件下载完成");
} catch (IOException e) {
e.printStackTrace();
}
try (InputStream in = fileUrl.openStream();
FileOutputStream out = new FileOutputStream("sample.pdf")) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
System.out.println("文件下载完成");
} catch (IOException e) {
e.printStackTrace();
}
示例 2:调用 REST API
实例
URL apiUrl = new URL("https://api.example.com/data?param1=value1");
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(apiUrl.openStream()))) {
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
System.out.println("API 响应: " + response.toString());
} catch (IOException e) {
e.printStackTrace();
}
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(apiUrl.openStream()))) {
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
System.out.println("API 响应: " + response.toString());
} catch (IOException e) {
e.printStackTrace();
}
注意事项
- 异常处理:URL 构造方法可能抛出 MalformedURLException,网络操作可能抛出 IOException
- 安全性:避免从不可信的来源构造 URL
- 性能:频繁的网络请求应考虑使用连接池
- 编码:确保正确处理 URL 编码,特别是包含非 ASCII 字符时
点我分享笔记