从 URL 字符串中提取主机名/域名 [英] Extract host name/domain name from URL string
问题描述
我有一个类似 http://hostname:port_no/control/login.jsp
的 URL.
I have a URL like http://hostname:port_no/control/login.jsp
.
我将上述 url 存储在某个字符串中.现在,我需要从字符串中提取 hostname
.
I have the above url stored in some String.Now, I need to extract hostname
from the String.
我在我的 Java 代码中这样做
I am doing like this in my Java code
String domain = url.substring(url.indexOf('/') + 2, url.lastIndexOf(':'));
我想知道是否有更好的方法来做同样的事情.
I want to know if there is any better way to do the same.
推荐答案
您可以使用 java.net.URI
-class 从字符串中提取主机名.
You can use the java.net.URI
-class to extract the hostname from the string.
下面是一种可以从字符串中提取主机名的方法.
Here below is a method from which you can extract your hostname from a string.
public String getHostName(String url) {
URI uri = new URI(url);
String hostname = uri.getHost();
// to provide faultproof result, check if not null then return only hostname, without www.
if (hostname != null) {
return hostname.startsWith("www.") ? hostname.substring(4) : hostname;
}
return hostname;
}
以上为您提供了主机名,如果您的主机名确实以 hostname.com/...
或 www.hostname.com/...
开头,则它是万无一失的>,它将返回主机名".
This above gives you the hostname, and is faultproof if your hostname does start with either hostname.com/...
or www.hostname.com/...
, which will return with 'hostname'.
如果给定的 url
无效(未定义的主机名),则返回 null.
If the given url
is invalid (undefined hostname), it returns with null.
这篇关于从 URL 字符串中提取主机名/域名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!