问题描述
在 Java 中检查 URL 是否有效的最佳方法是什么?
What is the best way to check if a URL is valid in Java?
如果尝试调用 new URL(urlString)
并捕获 MalformedURLException
,但它似乎对以 http://.
If tried to call
new URL(urlString)
and catch a MalformedURLException
, but it seems to be happy with anything that begins with http://
.
我不关心建立连接,只关心有效性.有没有办法做到这一点?Hibernate Validator 中的注释?我应该使用正则表达式吗?
I'm not concerned about establishing a connection, just validity. Is there a method for this? An annotation in Hibernate Validator? Should I use a regex?
可接受的 URL 的一些示例是
http://***
和 http://我最喜欢的网站!
.
Some examples of accepted URLs are
http://***
and http://my favorite site!
.
推荐答案
考虑使用 Apache Commons UrlValidator 类
UrlValidator urlValidator = new UrlValidator();
urlValidator.isValid("http://my favorite site!");
您可以设置几个属性来控制此类的行为,默认情况下接受
http
、https
和ftp
.
There are several properties that you can set to control how this class behaves, by default
http
, https
, and ftp
are accepted.
这篇关于如何在 Java 中检查有效的 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!