且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Java 中验证 URL

更新时间:2023-02-26 12:56:47

为了社区的利益,因为这个帖子在搜索时在 Google 上名列前茅
"url 验证器 java"

捕获异常代价高昂,应尽可能避免.如果您只想验证您的字符串是否是有效的 URL,您可以使用 UrlValidator 类来自 Apache Commons Validator 项目.

Catching exceptions is expensive, and should be avoided when possible. If you just want to verify your String is a valid URL, you can use the UrlValidator class from the Apache Commons Validator project.

例如:

String[] schemes = {"http","https"}; // DEFAULT schemes = "http", "https", "ftp"
UrlValidator urlValidator = new UrlValidator(schemes);
if (urlValidator.isValid("ftp://foo.bar.com/")) {
   System.out.println("URL is valid");
} else {
   System.out.println("URL is invalid");
}