题
我需要提取URL的顶级域,我得到了他的 http://publicsuffix.org/index.html
Java实施在 http://guava-libraries.googlecode.com
而且我找不到任何示例来提取域名
say example..
example.google.com
returns google.com
and bing.bing.bing.com
returns bing.com
任何人都可以告诉我如何使用此库以一个示例实现...。
解决方案
在我看来就像 InternetDomainName.topprivatedomain() 做 确切地 你想要什么。 Guava保留了公共后缀列表(基于Mozilla在PublicSuffix.org上的列表),该列表用来确定主机的公共后缀部分是什么……顶级私人域是公共后缀加上其第一个孩子。
这是一个快速示例:
public class Test {
public static void main(String[] args) throws URISyntaxException {
ImmutableList<String> urls = ImmutableList.of(
"http://example.google.com", "http://google.com",
"http://bing.bing.bing.com", "http://www.amazon.co.jp/");
for (String url : urls) {
System.out.println(url + " -> " + getTopPrivateDomain(url));
}
}
private static String getTopPrivateDomain(String url) throws URISyntaxException {
String host = new URI(url).getHost();
InternetDomainName domainName = InternetDomainName.from(host);
return domainName.topPrivateDomain().name();
}
}
运行此代码打印:
http://example.google.com -> google.com http://google.com -> google.com http://bing.bing.bing.com -> bing.com http://www.amazon.co.jp/ -> amazon.co.jp
其他提示
我最近实施了 公共后缀列表API:
PublicSuffixList suffixList = new PublicSuffixListFactory().build();
assertEquals(
"google.com", suffixList.getRegistrableDomain("example.google.com"));
assertEquals(
"bing.com", suffixList.getRegistrableDomain("bing.bing.bing.com"));
assertEquals(
"amazon.co.jp", suffixList.getRegistrableDomain("www.amazon.co.jp"));
编辑:对不起,我已经太快了。我没有想到CO.JP。 co.uk,等等。您将需要从某个地方获得可能的TLD列表。你也可以看一下 http://commons.apache.org/validator/ 验证一个tld。
我认为这样的事情应该起作用:但是也许存在一些Java标准功能。
String url = "http://www.foobar.com/someFolder/index.html";
if (url.contains("://")) {
url = url.split("://")[1];
}
if (url.contains("/")) {
url = url.split("/")[0];
}
// You need to get your TLDs from somewhere...
List<String> magicListofTLD = getTLDsFromSomewhere();
int positionOfTLD = -1;
String usedTLD = null;
for (String tld : magicListofTLD) {
positionOfTLD = url.indexOf(tld);
if (positionOfTLD > 0) {
usedTLD = tld;
break;
}
}
if (positionOfTLD > 0) {
url = url.substring(0, positionOfTLD);
} else {
return;
}
String[] strings = url.split("\\.");
String foo = strings[strings.length - 1] + "." + usedTLD;
System.out.println(foo);
不隶属于 StackOverflow