Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

java - Get domain without subdomain from a URL

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...