如何在Java中检查有效的URL?

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可以接受这些属性.

  • 它似乎不适用于较新的域名,如.london等 (7认同)

小智 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)

  • @SonuOommen 也许是因为 `new URL(http://google)` 是有效的^^ 我们公司有很多像这样的内部域 (4认同)
  • 好一个。仅使用新的 URL(名称)即可接受几乎所有内容。url.toURI(); 正是开发人员正在寻找的东西 - 无需使用其他库/框架! (2认同)
  • 这也不适用于格式错误的 URL,例如 http:/google.com。我使用了来自 Apache Commons 的 UrlValidator。 (2认同)
  • 这实在是太危险了。我看到还有很多其他文章都有这个例子。`URL u = new URL(http://google).toURI();` 不会抛出异常。 (2认同)

use*_*621 6

我想发布这篇文章作为对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)

您可以从那里轻松构建自己的验证器.


And*_*gin 5

我最喜欢的方法,没有外部库:

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)

  • 实际查询 URL 可能会导致更改、操作或跟踪。OP 希望在不进行查询的情况下检查有效性。例如,也许这是现在存储并稍后执行,并合理保证它是有效的。 (3认同)