我需要浏览大量字符串 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/