17

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.

James Smith
  • 871
  • 2
  • 8
  • 7

3 Answers3

21

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.

Dan
  • 1,041
  • 1
  • 12
  • 32
  • 4
    Note that this class is in the Google Guava library – nerdherd Sep 08 '14 at 03:44
  • 2
    Thanks for the good info! Using Selenium WebDriver which includes this library in the standalone jar so was able to reference it. Mind you, ".name" will not work as it's a private variable. http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/net/InternetDomainName.html – Lukus Nov 20 '14 at 17:08
  • @Lukus That's correct. I was writing this in groovy. – Dan May 28 '15 at 17:26
  • Not anymore with update version do this InternetDomainName.from(request.getServerName()).topPrivateDomain().toString() – Dima Oct 28 '16 at 22:44
1

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

Tinus Tate
  • 2,237
  • 2
  • 12
  • 33
1

The above solutions require you to add Guava. If you use OkHttp or Retrofit, you can also use

PublicSuffixDatabase.get().getEffectiveTldPlusOne("test.blogspot.com")

This gives you blogspot.com

crysxd
  • 3,177
  • 20
  • 32