Get domain without subdomain from a URL

北战南征 提交于 2019-12-19 05:12:31

问题


What is the proper way to get the domain from a URL without the subdomains?

In Java, from a string you can make a new URL(urlString) and call getHost() on the URL, but you have subdomains with it.

The problem is because there can be hosts like: subhost.example.com and subhost.example.co.uk

There are several other of these two part domains like co.uk (see the list on https://wiki.mozilla.org/TLD_List).

It seems to me the only correct way to get only the domain is to do a search through the TLD list, remove the TLD from the end of the host, and take away everything before the last period in the host. Is there an existing method that does this? I didn't see one in java.net.URL, and I checked apache commons a bit but couldn't find one there.


回答1:


I know this is a few years late but if anyone stumbles across this question try the following:

InternetDomainName.from("subhost.example.co.uk").topPrivateDomain().name

The above will return example.co.uk.




回答2:


Not sure if the above answer is correct:

InternetDomainName.from("test.blogspot.com").topPrivateDomain() -> test.blogspot.com

This works better in my case:

InternetDomainName.from("test.blogspot.com").topDomainUnderRegistrySuffix() -> blogspot.com

Details: https://github.com/google/guava/wiki/InternetDomainNameExplained



来源:https://stackoverflow.com/questions/3199862/get-domain-without-subdomain-from-a-url

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!