在Java中检查URL是否有效的最佳方法是什么?
如果尝试调用new URL(urlString)
并捕获MalformedURLException
,但它似乎对任何以http://
开头的内容都很满意。
我关心的不是建立连接,而是有效性。有什么方法可以解决这个问题吗?Hibernate Validator中的注解?我应该使用正则表达式吗?
编辑:可接受的URL的一些示例是http://***
和http://my favorite site!
。
发布于 2010-02-10 00:44:57
考虑使用Apache Commons UrlValidator class
UrlValidator urlValidator = new UrlValidator();
urlValidator.isValid("http://my favorite site!");
您可以设置几个属性来控制该类的行为,默认情况下接受http
、https
和ftp
。
发布于 2011-04-20 00:03:12
以下是我尝试并发现有用的方法,
URL u = new URL(name); // this would check for the protocol
u.toURI(); // does the extra checking required for validation of URI
发布于 2012-12-20 02:26:02
我很想把这篇文章作为评论贴到Tendayi Mawushe's answer上,但我担心篇幅不够;)
这是Apache Commons UrlValidator source中的相关部分。
/**
* This expression derived/taken from the BNF for URI (RFC2396).
*/
private static final String URL_PATTERN =
"/^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?/";
// 12 3 4 5 6 7 8 9
/**
* Schema/Protocol (ie. http:, ftp:, file:, etc).
*/
private static final int PARSE_URL_SCHEME = 2;
/**
* Includes hostname/ip and port number.
*/
private static final int PARSE_URL_AUTHORITY = 4;
private static final int PARSE_URL_PATH = 5;
private static final int PARSE_URL_QUERY = 7;
private static final int PARSE_URL_FRAGMENT = 9;
您可以很容易地从那里构建自己的验证器。
https://stackoverflow.com/questions/2230676
复制相似问题