从 URL 获取没有子域的域 [英] Get domain without subdomain from a URL

查看:23
本文介绍了从 URL 获取没有子域的域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从没有子域的 URL 获取域的正确方法是什么?

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

在 Java 中,您可以根据字符串创建一个新的 URL(urlString) 并在该 URL 上调用 getHost(),但您有子域.

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

问题是因为可能有这样的主机:子主机.example.com和subhost.example.co.uk

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

这两个部分中还有其他几个域,例如 co.uk(请参阅 https://wiki 上的列表.mozilla.org/TLD_List).

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

在我看来,唯一正确获取域的方法是通过 TLD 列表进行搜索,从主机的末尾删除 TLD,并在主机的最后一段之前删除所有内容.是否有一种现有的方法可以做到这一点?我在 java.net.URL 中没有看到,我查了一下 apache commons 但在那里找不到.

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.

推荐答案

我知道这已经晚了几年,但如果有人偶然发现这个问题,请尝试以下操作:

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

以上将返回example.co.uk.

The above will return example.co.uk.

这篇关于从 URL 获取没有子域的域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆