java - 从 URL 获取域名/主机名的最快方法是什么?

标签 java url dns

我需要浏览大量字符串 url 并从中提取域名。

例如:

http://www.stackoverflow.com/questions 将提取 www.stackoverflow.com

我最初使用的是 new URL(theUrlString).getHost(),但 URL 对象初始化会为该过程增加大量时间,而且似乎没有必要。

有没有更快的方法来提取主机名并且同样可靠?

谢谢

编辑: 我的错误,是的 www.将包含在上面的域名示例中。此外,这些 url 可能是 http 或 https

最佳答案

如果你想处理 https 等,我建议你这样做:

int slashslash = url.indexOf("//") + 2;
domain = url.substring(slashslash, url.indexOf('/', slashslash));

请注意,这包括 www 部分(就像 URL.getHost() 所做的那样),它实际上是域名的一部分。

通过评论请求编辑

这里有两种可能有用的方法:

/**
 * Will take a url such as http://www.stackoverflow.com and return www.stackoverflow.com
 * 
 * @param url
 * @return
 */
public static String getHost(String url){
    if(url == null || url.length() == 0)
        return "";

    int doubleslash = url.indexOf("//");
    if(doubleslash == -1)
        doubleslash = 0;
    else
        doubleslash += 2;

    int end = url.indexOf('/', doubleslash);
    end = end >= 0 ? end : url.length();

    int port = url.indexOf(':', doubleslash);
    end = (port > 0 && port < end) ? port : end;

    return url.substring(doubleslash, end);
}


/**  Based on : http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.3_r1/android/webkit/CookieManager.java#CookieManager.getBaseDomain%28java.lang.String%29
 * Get the base domain for a given host or url. E.g. mail.google.com will return google.com
 * @param host 
 * @return 
 */
public static String getBaseDomain(String url) {
    String host = getHost(url);

    int startIndex = 0;
    int nextIndex = host.indexOf('.');
    int lastIndex = host.lastIndexOf('.');
    while (nextIndex < lastIndex) {
        startIndex = nextIndex + 1;
        nextIndex = host.indexOf('.', startIndex);
    }
    if (startIndex > 0) {
        return host.substring(startIndex);
    } else {
        return host;
    }
}

关于java - 从 URL 获取域名/主机名的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4826061/

相关文章:

c++ - Qt 中 `:/foo` 、 `qrc:/foo` 和 `qrc:///foo` 路径之间的区别

java - 使用 java : corrupted data 从 FTP 站点下载文件

mysql - 如何统计MySQL中的URL域?

javascript - 在 AJAX 请求中更新域名的 DNS

php - 如何以编程方式在共享主机计划上创建插件域

java - 如何配置Spring Boot应用程序以支持UTF-8和GBK编码?

java - 何时使用 for (int i =0; ; )/for-each/iterator 遍历列表

MySQL:错误 2003 与同一本地网络上的虚拟机失去连接

java - Android 方法调用跟踪

java - 如何使字段成为 BLOB 而不是 TINYBLOB?