Eri*_*son 86 java validation url
检查URL在Java中是否有效的最佳方法是什么?
如果试图打电话new URL(urlString)
并抓住一个MalformedURLException
,但似乎对任何开头的东西感到满意http://
.
我不关心建立联系,只关心有效性.有这个方法吗?Hibernate Validator中的注释?我应该使用正则表达式吗?
编辑: 接受的URL的一些示例是http://***
和http://my favorite site!
.
Ten*_*she 94
考虑使用Apache Commons UrlValidator类
UrlValidator urlValidator = new UrlValidator();
urlValidator.isValid("http://my favorite site!");
Run Code Online (Sandbox Code Playgroud)
默认情况下http
,您可以设置几个属性来控制此类的行为https
,并且ftp
可以接受这些属性.
小智 56
这是我尝试过的方式,发现有用,
URL u = new URL(name); // this would check for the protocol
u.toURI(); // does the extra checking required for validation of URI
Run Code Online (Sandbox Code Playgroud)
我想发布这篇文章作为对Tendayi Mawushe答案的评论,但我担心没有足够的空间;)
这是Apache Commons UrlValidator 源代码的相关部分:
/**
* 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;
Run Code Online (Sandbox Code Playgroud)
您可以从那里轻松构建自己的验证器.
我最喜欢的方法,没有外部库:
try {
URI uri = new URI(name);
// perform checks for scheme, authority, host, etc., based on your requirements
if ("mailto".equals(uri.getScheme()) {/*Code*/}
if (uri.getHost() == null) {/*Code*/}
} catch (URISyntaxException e) {
}
Run Code Online (Sandbox Code Playgroud)
小智 5
最“万无一失”的方法是检查 URL 的可用性:
public boolean isURL(String url) {
try {
(new java.net.URL(url)).openStream().close();
return true;
} catch (Exception ex) { }
return false;
}
Run Code Online (Sandbox Code Playgroud)