import com.google.common.net.InternetDomainName;
public static void main(String[] args) { InternetDomainName top = InternetDomainName.from("keyupgrade.spaceforupdate.download").topPrivateDomain(); System.out.println(top); }
比如我写的:
private String extractDomain(String domain) { try { return InternetDomainName.from(domain).topPrivateDomain().name(); } catch (java.lang.IllegalStateException e) { String[] levels = domain.split("\."); // if (levels.length > 1) { // return levels[levels.length - 2] + "." + levels[levels.length - 1]; // } else { return levels[levels.length-1]; // } } catch (java.lang.IllegalArgumentException e){ String[] levels = domain.split("\."); return levels[levels.length-1]; } }
参考:
https://stackoverflow.com/questions/45046265/internetdomainname-and-publicsuffix-list
https://github.com/google/guava/blob/master/guava/src/com/google/common/net/InternetDomainName.java
https://stackoverflow.com/questions/7217271/extract-main-domain-name-from-a-given-url