在Java中,检查URL是否有效的最佳方法是什么?
如果尝试调用new URL(urlString)
并捕获MalformedURLException
,但它似乎会接受任何以http://
开头的内容。
我不关心建立连接,只关心有效性。有没有这方面的方法?Hibernate验证器中的注释?我应该使用正则表达式吗?
编辑:一些被接受的URL示例是http://***
和http://my favorite site!
。
在Java中,检查URL是否有效的最佳方法是什么?
如果尝试调用new URL(urlString)
并捕获MalformedURLException
,但它似乎会接受任何以http://
开头的内容。
我不关心建立连接,只关心有效性。有没有这方面的方法?Hibernate验证器中的注释?我应该使用正则表达式吗?
编辑:一些被接受的URL示例是http://***
和http://my favorite site!
。
考虑使用 Apache Commons UrlValidator 类
UrlValidator urlValidator = new UrlValidator();
urlValidator.isValid("http://my favorite site!");
有几个属性可以设置来控制这个类的行为,默认情况下接受http
、https
和ftp
。
local
等。 - user9461715new URL(name).toURI()
成为了解决方案。 - Avec这是我尝试过的一种有用的方法,
URL u = new URL(name); // this would check for the protocol
u.toURI(); // does the extra checking required for validation of URI
URL u = new URL(http://google).toURI();
不会抛出异常。 - Sonu Oommennew URL(http://google)
是合法的^^
我们公司有很多像这样的内部域名 - user43968/**
* 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;
您可以轻松地从那里构建自己的验证器。
public boolean isURL(String url) {
try {
(new java.net.URL(url)).openStream().close();
return true;
} catch (Exception ex) { }
return false;
}
我最喜欢的方法是不使用外部库:
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) {
}
final static Set<String> protocols, protocolsWithHost;
static {
protocolsWithHost = new HashSet<String>(
Arrays.asList( new String[]{ "file", "ftp", "http", "https" } )
);
protocols = new HashSet<String>(
Arrays.asList( new String[]{ "mailto", "news", "urn" } )
);
protocols.addAll(protocolsWithHost);
}
public static boolean isURI(String str) {
int colon = str.indexOf(':');
if (colon < 3) return false;
String proto = str.substring(0, colon).toLowerCase();
if (!protocols.contains(proto)) return false;
try {
URI uri = new URI(str);
if (protocolsWithHost.contains(proto)) {
if (uri.getHost() == null) return false;
String path = uri.getPath();
if (path != null) {
for (int i=path.length()-1; i >= 0; i--) {
if ("?<>:*|\"".indexOf( path.charAt(i) ) > -1)
return false;
}
}
}
return true;
} catch ( Exception ex ) {}
return false;
}
URI
的源代码,可以判断public URL(URL context, String spec, URLStreamHandler handler)
constructor比其他构造函数执行更多的验证。你可以尝试使用它,但效果可能因人而异。
似乎有一个由Yonatan Matalon创建的UrlUtil包。引用其API:
isValidWebPageAddress(java.lang.String address, boolean validateSyntax,
boolean validateExistance)
Checks if the given address is a valid web page address.
在 org.apache.xerces.util.URI 中也有一个函数。
isWellFormedAddress(java.lang.String address)
URL
构造函数中被接受但不是有效的 URL 的例子吗? - uckelmanhttp://***
" 可以使用。 "http://我最喜欢的网站!
" 也可以使用。但我无法让它抛出异常(当http://在开头时)。 - Eric Wilson