java - 从给定的url获取域名

标签 java url

给定一个 URL,我想提取域名(它不应包含“www”部分)。网址可以包含 http/https。这是我写的java代码。虽然它似乎工作正常,但有没有更好的方法或者有一些边缘情况可能会失败。

public static String getDomainName(String url) throws MalformedURLException{
    if(!url.startsWith("http") && !url.startsWith("https")){
         url = "http://" + url;
    }        
    URL netUrl = new URL(url);
    String host = netUrl.getHost();
    if(host.startsWith("www")){
        host = host.substring("www".length()+1);
    }
    return host;
}

输入:http://google.com/blah

输出:google.com

最佳答案

如果要解析 URL,请使用 java.net.URI . java.net.URL 有很多问题——它的 equals 方法进行 DNS 查找,这意味着使用它的代码在与不受信任的情况下使用时可能容易受到拒绝服务攻击输入。

"Mr. Gosling -- why did you make url equals suck?"解释了一个这样的问题。只要养成使用 java.net.URI 的习惯。

public static String getDomainName(String url) throws URISyntaxException {
    URI uri = new URI(url);
    String domain = uri.getHost();
    return domain.startsWith("www.") ? domain.substring(4) : domain;
}

应该做你想做的。


Though It seems to work fine, is there any better approach or are there some edge cases, that could fail.

您编写的代码对于有效的 URL 失败:

  • httpfoo/bar -- 具有以 http 开头的路径组件的相对 URL。
  • HTTP://example.com/ -- 协议(protocol)不区分大小写。
  • //example.com/ -- 带有主机的协议(protocol)相对 URL
  • www/foo -- 一个以 www
  • 开头的路径组件的相对 URL
  • wwwexample.com -- 不以www.开头但以www开头的域名。

分层 URL 具有复杂的语法。如果您在没有仔细阅读 RFC 3986 的情况下尝试使用自己的解析器,您可能会弄错。只需使用内置于核心库中的那个即可。

如果您确实需要处理 java.net.URI 拒绝的杂乱输入,请参阅 RFC 3986附录 B:

Appendix B. Parsing a URI Reference with a Regular Expression

As the "first-match-wins" algorithm is identical to the "greedy" disambiguation method used by POSIX regular expressions, it is natural and commonplace to use a regular expression for parsing the potential five components of a URI reference.

The following line is the regular expression for breaking-down a well-formed URI reference into its components.

  ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
   12            3  4          5       6  7        8 9

The numbers in the second line above are only to assist readability; they indicate the reference points for each subexpression (i.e., each paired parenthesis).

关于java - 从给定的url获取域名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9607903/

相关文章:

java - 在 BlueJ 中使用负无穷大(垂直)斜率

image - WordPress获取图像URL(当前使用wp_get_attachment_url)

php - 基于 PHP 语言的 URL 别名

php - 使用 PHP/CodeIgniter 动态检测动画 GIF

python - 使用 Python 和正则表达式查找正确的 URL

java - 寻找一种智能且快速的搜索算法

java - 在 Java 中嵌入 Office

java - 如何将简单的 SQL 连接查询转换为 HQL

Java - 声明顺序中的反射 getDeclaredMethods 奇怪的行为

python - 如何对列表中的各个条目使用 split