我只想显示网站名称。
我不想显示“.com”或“us.cnn.com”或“www.bbc.co.uk”,只显示网站名称,如“cnn”或“bbc”。
我的代码:
private String getHostName(String urlInput) {
urlInput = urlInput.toLowerCase();
String hostName = urlInput;
if (!urlInput.equals("")) {
if (urlInput.startsWith("http") || urlInput.startsWith("https")) {
try {
URL netUrl = new URL(urlInput);
String host = netUrl.getHost();
if (host.startsWith("www")) {
hostName = host.substring("www".length() + 1);
} else {
hostName = host;
}
} catch (MalformedURLException e) {
hostName = urlInput;
}
} else if (urlInput.startsWith("www")) {
hostName = urlInput.substring("www".length() + 1);
}
return hostName;
} else {
return "";
}
}
输入
http://www.bbc.co.uk/news/world-us-canada-39018776"
http://us.cnn.com/2017/02/18/politics/john-mccain-donald-trump-dictators/index.html"
http://bigstory.ap.org/article/d5dd5962fc4d42b195117ca63e0ba9af/revived-rally-trump-turns-back-governing
输出
www.bbc.co.uk
us.cnn.com
bigstory.ap.org
我只想从中提取“bbc”、“cnn”和“ap”名称。
最佳答案
您可以使用 java.net.URI
-class 从字符串中提取主机名。
示例代码:
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;
}
上面的内容为您提供了主机名,如果您的主机名确实以 google.com/...
或 www.google.com/...
开头,则可以防止出错>,它将返回“google”。
如果给定的 url
无效(未定义的主机名),则返回 null。
关于java - 如何仅从 URL 字符串中提取网站名称而不是 www.和 .com 与它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42325169/