上一篇
在Java中,可通过
java.net.URL类解析URL字符串,使用
getProtocol()、
getHost()、
getPath()等方法获取协议、域名、路径等部分;或直接通过字符串操作如
substring()结合正则表达式截取所需片段,推荐使用
URL类避免解析错误。
使用 java.net.URL 类(标准库推荐)
URL 类提供结构化解析,安全且无需第三方依赖:
import java.net.URL;
public class UrlParser {
public static void main(String[] args) throws Exception {
String fullUrl = "https://www.example.com:8080/path/to/page?query=param#section";
URL url = new URL(fullUrl);
System.out.println("协议: " + url.getProtocol()); // https
System.out.println("域名: " + url.getHost()); // www.example.com
System.out.println("端口: " + url.getPort()); // 8080(未指定返回-1)
System.out.println("路径: " + url.getPath()); // /path/to/page
System.out.println("查询参数: " + url.getQuery()); // query=param
System.out.println("锚点: " + url.getRef()); // section
}
}
优点:自动处理编码和格式验证,避免手动错误。
注意:需处理 MalformedURLException 异常。
正则表达式(灵活匹配)
适合提取特定部分(如域名):
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExtractor {
public static void main(String[] args) {
String url = "https://subdomain.example.com/path";
Pattern pattern = Pattern.compile("^(https?)://([^/?#]+)");
Matcher matcher = pattern.matcher(url);
if (matcher.find()) {
System.out.println("协议: " + matcher.group(1)); // https
System.out.println("域名: " + matcher.group(2)); // subdomain.example.com
}
}
}
优点:高度定制化。
缺点:复杂URL可能匹配失败,维护成本高。

字符串分割(简单场景适用)
仅适用于格式固定的URL:
public class StringSplit {
public static void main(String[] args) {
String url = "https://example.com/resource";
String protocol = url.substring(0, url.indexOf("://")); // https
String domain = url.substring(url.indexOf("://") + 3);
domain = domain.contains("/") ? domain.substring(0, domain.indexOf("/")) : domain;
System.out.println("协议: " + protocol); // https
System.out.println("域名: " + domain); // example.com
}
}
缺点:无法处理端口、参数等复杂结构,易出错。
Apache Commons Validator(第三方库)
适用于验证和提取:

import org.apache.commons.validator.routines.UrlValidator;
import org.apache.commons.validator.routines.UrlValidator;
public class CommonsValidator {
public static void main(String[] args) {
String url = "http://example.com";
UrlValidator validator = new UrlValidator();
if (validator.isValid(url)) {
// 结合java.net.URL进一步解析
// 参考方法1的解析逻辑
}
}
}
依赖添加(Maven):
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.7</version>
</dependency>
优点:提供URL验证,常与 java.net.URL 配合使用。

方法对比与建议
| 方法 | 适用场景 | 安全性 | 复杂度 |
|---|---|---|---|
java.net.URL |
需完整解析URL各部分 | 高 | 低 |
| 正则表达式 | 提取特定片段(如域名) | 中 | 高 |
| 字符串分割 | 格式固定的简单URL | 低 | 低 |
| Apache Commons | 需验证URL合法性 | 高 | 中 |
最佳实践:
- 优先使用
java.net.URL:标准库方法最安全可靠。 - 涉及用户输入时,始终捕获
MalformedURLException异常。 - 避免手动字符串切割:易忽略边缘情况(如默认端口、特殊符号)。
- 标准库解析是核心方案,覆盖90%场景。
- 正则表达式适用于高级文本提取。
- 第三方库在验证场景中补充使用。
- 避免重复造轮子,优先利用Java内置能力。
引用说明:本文代码基于 Java 17 API 和 Apache Commons Validator 1.7 官方文档实现,正则表达式参考了RFC 3986标准中对URI结构的定义。
